cache缓存

-(NSCache *)cache

{

if (_cache == nil) {

_cache = [[NSCache alloc]init];

_cache.totalCostLimit = 5;//总成本数是5 ,如果发现存的数据超过中成本那么会自动回收之前的对象

_cache.delegate = self;

}

return _cache;

}

//存数据

- (IBAction)addBtnClick:(id)sender

{

//NSCache的Key只是对对象进行Strong引用,不是拷贝(和可变字典的区别)

for (NSInteger i = 0; i<10; i++) {

NSData *data = [NSData dataWithContentsOfFile:@"/Users/beidou/Desktop/29381f30e924b8995d7368d66a061d950b7bf695.jpg"];

//cost:成本

[self.cache setObject:data forKey:@(i) cost:1];

NSLog(@"存数据%zd",i);

}

}

//取数据

- (IBAction)checkBtnClick:(id)sender

{

//    NSLog(@"+++++++++++++++");

//    for (NSInteger i = 0; i<10; i++) {

//        NSData *data = [self.cache objectForKey:@(i)];

//        if (data) {

//            NSLog(@"取出数据%zd",i);

//        }

//    }

NSData *data = [self.cache objectForKey:@(8)];

if (data) {

NSLog(@"取出数据%@",data);

}

}

//删除数据

- (IBAction)removeBtnClick:(id)sender

{

[self.cache removeAllObjects];

}

#pragma mark ----------------------

#pragma mark NSCacheDelegate

//即将回收对象的时候调用该方法

-(void)cache:(NSCache *)cache willEvictObject:(id)obj

{

NSLog(@"回收%zd",[obj length]);

}

你可能感兴趣的:(cache缓存)