#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong)NSCache *cache;
@end
@implementation ViewController
-(NSCache *)cache{
if (_cache == nil) {
_cache = [[NSCache alloc]init];
//设置数量限制,删除之前缓存的内容
_cache.countLimit = 15;
//设置代理
_cache.delegate = self;
}
return _cache;
}
//开发测试时使用,一般不用:缓存中的对象将要被删除,调用此方法
-(void)cache:(NSCache *)cache willEvictObject:(id)obj{
NSLog(@"要删除的对象obj----%@",obj);
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
for (int i = 0; i<20; i++) {
NSString *str = [NSString stringWithFormat:@"hello - NO.%d",i];
[self.cache setObject:str forKey:@(i)];
/*@(i):[NSNumber numberWithInt:i]
*@[]:快速加数组
*@{}:快速加字典 */
}
for (int i = 0; i<20; i++) {
NSString *str = [self.cache objectForKey:@(i)];
NSLog(@"%@",str);
}
}