NSCache 类似于 NSMutableDictionary, 但是它会自动移除对象来释放内存,并且可设置缓存的数目与内存大小限制的方式,处理数据线程安全,当内存警告时内部自动清理部分缓存数据。
NSCache 常用属性与方法
//// 属性
// 代理
@property (assign) id<NSCacheDelegate>delegate;
// 是否在内存销毁时丢弃该对象
@property BOOL evictsObjectsWithDiscardedContent;
// 最大缓存数量
@property NSUInteger totalCostLimit;
//// 代理方法
//若obj需持久化存储,则可在这进行其他操作
- (void)cache:(NSCache *)cache willEvictObject:(id)obj;
触发willEvict:代理方法的事件:removeObjectForKey、缓存超过设定的上限、App不活跃、系统内存爆炸。
NSCache 的用法
#import "viewController.h"
@interface viewController () <NSCacheDelegate>
@property (nonatomic ,strong) NSCache *cache;
@end
@implementation viewController
- (void)viewDidLoad {
[super viewDidLoad];
_cache = [NSCache new];
_cache.totalCostLimit = 5;
_cache.delegate = self;
[self toCache];
}
- (void)toCache {
for (int i = 0; i<10; i++) {
NSString *obj = [NSString stringWithFormat:@"object--%d",i];
[self.cache setObject:obj forKey:@(i) cost:1];
NSLog(@"%@ cached",obj);
}
}
#pragma mark - NSCacheDelegate
- (void)cache:(NSCache *)cache willEvictObject:(id)obj {
//evict : 驱逐
NSLog(@"%@", [NSString stringWithFormat:@"%@ will be evict",obj]);
}
@end
//// 输出log
2021-05-18 09:30:56.485719+0800 CacheDemo[52839:214698] object--0 cached
2021-05-18 09:30:56.485904+0800 CacheDemo[52839:214698] object--1 cached
2021-05-18 09:30:56.486024+0800 CacheDemo[52839:214698] object--2 cached
2021-05-18 09:30:56.486113+0800 CacheDemo[52839:214698] object--3 cached
2021-05-18 09:30:56.486254+0800 CacheDemo[52839:214698] object--4 cached
2021-05-18 09:30:56.486382+0800 CacheDemo[52839:214698] object--0 will be evict
2021-05-18 09:30:56.486480+0800 CacheDemo[52839:214698] object--5 cached
2021-05-18 09:30:56.486598+0800 CacheDemo[52839:214698] object--1 will be evict
2021-05-18 09:30:56.486681+0800 CacheDemo[52839:214698] object--6 cached
2021-05-18 09:30:56.486795+0800 CacheDemo[52839:214698] object--2 will be evict
2021-05-18 09:30:56.486888+0800 CacheDemo[52839:214698] object--7 cached
2021-05-18 09:30:56.486995+0800 CacheDemo[52839:214698] object--3 will be evict
2021-05-18 09:30:56.487190+0800 CacheDemo[52839:214698] object--8 cached
2021-05-18 09:30:56.487446+0800 CacheDemo[52839:214698] object--4 will be evict
2021-05-18 09:30:56.487604+0800 CacheDemo[52839:214698] object--9 cached
NSCache可用于处理app中较简单的缓存操作,复杂的还需要借助其他三方库来实现。
网友评论