https://github.com/ibireme/YYCache
小数据存储:
1、plist(NSUserDefaults):主要是系统设置
2、cache 缓存(磁盘保存,以及内存缓存)
YYCache
sqlite3.0
1 存:存入内存的同时写入磁盘
2 读:1)先从内存读,有就直接拿来用;2)没有再从磁盘读,有就拿来用,顺便存到内存;3)还没有就返回空。
-1 总缓存(包括磁盘和内存)
// 建个小数据表
YYCache *cache = [YYCache cacheWithName:@"userInfo"];
// 存
[cache setObject:@"张三" forKey:@"name"];
// 检查 读取(直接读取,不存在则是 nil)
if ([cache containsObjectForKey:@"name"]) {
NSString *name = (NSString *)[cache objectForKey:@"name"];
NSLog(@"%@",[name class]);
}
// 删
[cache removeObjectForKey:@"name"];
[cache removeAllObjects];
- 2 只要内存 或者 只要磁盘存储
YYCache *cache = [YYCache cacheWithName:@"userInfo"];
YYDiskCache *diskCache = cache.diskCache;
YYMemoryCache *memoryCache = cache.memoryCache;
// diskCache memoryCache 与cache 存取方法一致!!
实际使用
一般用作 UserManager 单例,保存用户数据等。举个简单栗子
- 1 .h
@interface UserManager : NSObject
+ (instancetype)manager;
@property (nonatomic, copy, readonly) NSString *name;
@property (nonatomic, copy, readonly) NSString *gender;
@property (nonatomic, assign, readonly) NSInteger age;
@property (nonatomic, strong) UserModel *userModel;
- (void)updateUserInfo:(id)userInfo;
@end
- 2 .m
+ (instancetype)manager {
static UserManager *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[UserManager alloc] init];
});
return instance;
}
- (instancetype)init {
self = [super init];
if (self) {
self.userCache = [[YYCache alloc] initWithName:@"jyw.userInfo"];
}
return self;
}
- (void)updateUserInfo:(id)userInfo {
[self.userCache setObject:userInfo forKey:@"info"];
}
- (NSDictionary *)userInfo {
if (!_userInfo) {
id value = [self.userCache objectForKey:@"info"];
NSDictionary *userInfo = (NSDictionary *)value;
return userInfo;
}
return _userInfo;
}
- (UserModel *)userModel {
if (!_userModel) {
if (self.userInfo) {
UserModel *employeeModel = [UserModel mj_objectWithKeyValues:self.userInfo];
return employeeModel;
}
}
return _userModel;
}
- (NSString *)name {
return self.userModel.name;
}
- (NSString *)gender {
return self.userModel.gender;
}
- (NSInteger)age {
return self.userModel.age;
}
- 3 使用
NSDictionary *userInfo = @{@"name":@"张三",
@"gender":@"男",
@"age":@"18"};
[[UserManager manager] updateUserInfo:userInfo];
NSLog(@"%@",[UserManager manager].name);
NSLog(@"%@",[UserManager manager].gender);
NSLog(@"%zi",[UserManager manager].age);
1