NSCache的使用
Posted goodmorningmr
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NSCache的使用相关的知识,希望对你有一定的参考价值。
NSCache是苹果公司自己开发的缓存类,其使用方法简单,并且可以设置最大缓存数量,当超出最大数量时自动回收先放入的对象。NSCache是线程安全的,在使用时不用担心因线程而出现的数据错误。
NSCache的接口
- (nullableObjectType)objectForKey:(KeyType)key; //根据key取出某条数据
- (void)setObject:(ObjectType)obj forKey:(KeyType)key;// 0 cost //添加某条数据
- (void)setObject:(ObjectType)obj forKey:(KeyType)key cost:(NSUInteger)g; //添加某条数据并设置其占用的资源数目
- (void)removeObjectForKey:(KeyType)key; //删除某条数据
- (void)removeAllObjects; //删除所有数据
@property NSUInteger totalCostLimit; // 设置缓存大小限制
@property NSUInteger countLimit; // 设置总条数的限制
@property BOOL evictsObjectsWithDiscardedContent; //是否自动舍弃那些内存已经被丢弃的对象
- (void)cache:(NSCache *)cache willEvictObject:(id)obj; //代理方法当对象呗删除时调用
封装的管理器方法
.h中的代码
+ (instancetype)manager;
- (void)addDataArr:(NSArray *)dataArr modelStr:(NSString *)str;
- (NSArray *)getDataWithModelStr:(NSString *)str;
- (void)removeAllObjects;
.m中的代码
@property (nonatomic, strong) NSCache * cache;
+ (instancetype)manager
{
static CacheManager * manager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[CacheManager alloc] init];
manager.cache.totalCostLimit = 500; //设置总缓存数据大小
});
return manager;
}
- (NSArray *)getDataResultWithModelStr:(NSString *)str
{
NSArray * resulr = [self getDataWithModelStr:str];
if (resulr.count == 0) {
return nil;
}
return resulr;
}
- (void)refreshDataWithArr:(NSArray *)dataArr withStr:(NSString *)modelStr
{
[self removeObjectForKey:modelStr];
[self addDataArr:dataArr modelStr:modelStr];
}
//根据传入的model名称信息来添加数据
- (void)addDataArr:(NSArray *)dataArr modelStr:(NSString *)str {
if (dataArr.count == 0) return;
for (NSInteger i = 0; i < dataArr.count; i++) {
[self.cache setObject:dataArr[i] forKey:[NSString stringWithFormat:@"%@%ld", str,i] cost:1]; //添加内容到缓存中,并设置每个对象所占的大小
}
}
////取出缓存数据
- (NSArray *)getDataWithModelStr:(NSString *)str {
NSMutableArray * dataArr = @[].mutableCopy;
for (NSInteger i = 0; i < self.cache.countLimit; i++) {
NSObject * model = [_cache objectForKey:[NSString stringWithFormat:@"%@%ld", str,i]];
if (model) {
[dataArr addObject:model];
}else{
break;
}
}
return dataArr;
}
//删除某一key值下的所有数据
- (void)removeObjectForKey:(NSString *)key
{
for (NSInteger i = 0; i < self.cache.countLimit; i++) {
id model = [_cache objectForKey:[NSString stringWithFormat:@"%@%ld", key,i]];
if (model) {
[self.cache removeObjectForKey:[NSString stringWithFormat:@"%@%ld", key,i]];
}else{
return;
}
}
}
- (void)removeAllObjects
{
[self.cache removeAllObjects];
}
- (NSCache *)cache
{
if (!_cache) {
_cache = [[NSCache alloc] init];
_cache.delegate = self;
}
return _cache;
}
以上是关于NSCache的使用的主要内容,如果未能解决你的问题,请参考以下文章