NSCache相关
#import "ViewController.h"
@interface ViewController () <NSCacheDelegate>
@property (nonatomic,strong)NSCache *cache;
@property (nonatomic,strong)NSOperationQueue *queue;
@end
@implementation ViewController
- (NSCache *)cache
{
if(_cache == nil)
{
_cache = [[NSCache alloc]init];
//_cache.countLimit = 5;//设置最多可以缓存多少个对象
//_cache.totalCostLimit = 5;//设置缓存最大代价(成本),如果当前缓存达到最大代价(成本),会自动先回收之前的对象
_cache.delegate = self;
}
return _cache;
}
//存入缓存数据
- (IBAction)writeCache:(id)sender {
NSBlockOperation *download = [NSBlockOperation blockOperationWithBlock:^{
for(int i = 0; i < 10; i++)
{
NSURL *url = [NSURL URLWithString:@"http://p16.qhimg.com/dr/48_48_/t0125e8d438ae9d2fbb.png"];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self.cache setObject:data forKey:@(i)];
//[self.cache setObject:data forKey:@(i) cost:1];//存入缓存并设置代价(成本)
NSLog(@"---存入缓存 %d---",i);
NSLog(@"----save cache----%@",[NSThread currentThread]);
}];
}
}
NSLog(@"----download----%@",[NSThread currentThread]);
}];
self.queue = [[NSOperationQueue alloc]init];
[self.queue addOperation:download];
NSLog(@"%s",__func__);
}
//取出缓存数据
- (IBAction)checkCache:(id)sender {
for(int i = 0; i < 10; i++)
{
NSData *data = [self.cache objectForKey:@(i)];
if(data)
{
NSLog(@"---检查到缓存 %d---",i);
}
else
{
NSLog(@"---没有检查到缓存---");
}
}
}
//清除缓存数据
- (IBAction)clearCache:(id)sender {
[self.cache removeAllObjects];
NSLog(@"---缓存已清空---");
}
//代理方法,即将要回收对象时会调用
- (void)cache:(NSCache *)cache willEvictObject:(id)obj
{
NSData *data = (NSData*)obj;
NSLog(@"回收对象的长度%zd",[data length]);
}
@end
注意:NSCache的Key只是对对象进行strong引用,而不是copy,而NSDictionary的key是copy