#import "ViewController.h"
@interface ViewController () <NSCacheDelegate>
/// 全局的缓存池
@property (nonatomic,strong)NSCache *cache;
@end
@implementation ViewController
- (NSCache *)cache
{
if (_cache ==nil) {
_cache = [[NSCachealloc] init];
_cache.delegate =self;
// 设置缓存的个数(限额)
_cache.countLimit =5;
}
return_cache;
}
- (void)viewDidLoad {
[superviewDidLoad];
// 循环的向cache中添加对象
for (int i =0; i < 10; i++) {
NSString *str = [NSStringstringWithFormat:@"hello_%d",i+1];
NSLog(@"添加 %@",str);
NSString *key = [NSStringstringWithFormat:@"key_%d",i];
[self.cachesetObject:str forKey:key];
}
// 循环的取值
for (int i =0; i < 10; i++) {
NSString *key = [NSStringstringWithFormat:@"key_%d",i];
NSString *str = [self.cacheobjectForKey:key];
NSLog(@"获取 %@",str);
}
}
/// NSCache的代理方法,在对象将要从cache中移除的时候调用的
- (void)cache:(NSCache *)cache willEvictObject:(id)obj
{
NSLog(@"移除 %@",obj);
}
/// 在 didReceiveMemoryWarning方法中,移除了所有对象之后,再去做添加的操作
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
for (int i =0; i < 10; i++) {
NSString *str = [NSStringstringWithFormat:@"hello_%d",i+1];
NSLog(@"touchesBegan添加 %@",str);
NSString *key = [NSStringstringWithFormat:@"key_%d",i];
[self.cachesetObject:str forKey:key];
}
// 循环的取值
for (int i =0; i < 10; i++) {
NSString *key = [NSStringstringWithFormat:@"key_%d",i];
NSString *str = [self.cacheobjectForKey:key];
NSLog(@"touchesBegan获取 %@",str);
}
}
/// 此时会再重新的添加
- (IBAction)clickBtn:(id)sender
{
[self.cacheremoveAllObjects];
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// 注意 :一旦在 didReceiveMemoryWarning 调用移除全部对象的方法之后,那么这个cache永远不会再去添加对象
[self.cacheremoveAllObjects];
}