First, to achieve cache delegate class <NSCacheDelegate>
@Property (nonatomic, strong) NSCache * Cache;
Initialize cache class NSCache
- (NSCache *) Cache {
IF (_cache == nil) {
_cache = [[NSCache the alloc] the init];
// cache can store a total of how many
_cache.countLimit =. 5;
}
return _cache;
}
Then set the delegate, to which added data NSCache
// add the cache data
for (int I = 0; I <10; I ++) {
[in self.cache the setObject: [NSString stringWithFormat: @ "% D Hello", I] forKey: [NSString stringWithFormat: @ "% D H" , I]];
NSLog (@ "Add% @", [NSString stringWithFormat: @ "Hello% D", I]);
}
// the output buffer data
for (int i = 0; i <10; i ++) {
NSLog (@ "% @", [in self.cache objectForKey: [NSString stringWithFormat: @ "% D H", I]]);
}
// remove the one from NSCache when executed
- (void) Cache: (NSCache *) Cache willEvictObject: (ID) {obj
NSLog (@ "% @ removed from cache", 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]]);
}
}