首先实现缓存类的delegate <NSCacheDelegate>
@property (nonatomic, strong) NSCache *cache;
初始化缓存类NSCache
- (NSCache *)cache {
if (_cache == nil) {
_cache = [[NSCache alloc] init];
//缓存中总共可以存储多少条
_cache.countLimit = 5;
}
return _cache;
}
然后设置delegate,往NSCache里面添加数据
//添加缓存数据
for (int i = 0; i < 10; i++) {
[self.cache setObject:[NSString stringWithFormat:@"hello %d",i] forKey:[NSString stringWithFormat:@"h%d",i]];
NSLog(@"添加 %@",[NSString stringWithFormat:@"hello %d",i]);
}
//输出缓存中的数据
for (int i = 0; i < 10; i++) {
NSLog(@"%@",[self.cache objectForKey:[NSString stringWithFormat:@"h%d",i]]);
}
//将要从NSCache中移除一项的时候执行
- (void)cache:(NSCache *)cache willEvictObject:(id)obj {
NSLog(@"从缓存中移除 %@",obj);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.cache removeAllObjects];
//添加缓存数据
for (int i = 0; i < 10; i++) {
[self.cache setObject:[NSString stringWithFormat:@"hello %d",i] forKey:[NSString stringWithFormat:@"h%d",i]];
// NSLog(@"添加 %@",[NSString stringWithFormat:@"hello %d",i]);
}
//输出缓存中的数据
for (int i = 0; i < 10; i++) {
NSLog(@"%@",[self.cache objectForKey:[NSString stringWithFormat:@"h%d",i]]);
}
}