iOS NSCache使用

http://www.15yan.com/story/45toOUzFGlr/

NSCache可以设置数量限制,通过countLimit与 totalCostLimit来限制cache的数量或者限制cost。当缓存的数量超过countLimit,或者cost之和超过totalCostLimit,NSCache会自动释放部分缓存。

代码:

- (void)initView{

UIButton*btn = [UIButtonbuttonWithType:UIButtonTypeCustom];

btn.frame=CGRectMake(20,20,100,40);

btn.backgroundColor= [UIColorredColor];

[btnaddTarget:selfaction:@selector(btnClick:)forControlEvents:UIControlEventTouchDown];

[self.viewaddSubview:btn];

}

- (void)btnClick:(UIButton*)sender{

//[self imageViewPractice01];

NSData*data = [cacheobjectForKey:@"0"];

NSLog(@"Data0 size:%@",@(data.length));

NSData*data19 = [cacheobjectForKey:@"0"];

NSLog(@"data19 size:%@",@(data19.length));

NSData*data20 = [cacheobjectForKey:@"20"];

NSLog(@"Data20 size:%@",@(data20.length));

NSData*data21 = [cacheobjectForKey:@"21"];

NSLog(@"data21 size:%@",@(data21.length));

NSData*data47 = [cacheobjectForKey:@"47"];

NSLog(@"Data47 size:%@",@(data47.length));

NSData*data48 = [cacheobjectForKey:@"48"];

NSLog(@"Data48 size:%@",@(data48.length));

}

- (void)cachePractice{

cache= [[NSCachealloc]init];

//设置cache的最大数目

cache.countLimit=30;

//设置totalCostLimit,即每一项的cost之和的最大数目

cache.totalCostLimit=100;

NSURL*url = [[NSBundlemainBundle]URLForResource:@"pic_04"withExtension:@"jpeg"];

for(inti =0; i <50; i++) {

NSData*data = [NSDatadataWithContentsOfURL:url];

NSLog(@"Add data %@ size: %@",@(i),@(data.length));

//不设置cost

//[cache setObject:data forKey:[NSString stringWithFormat:@"%d",i]];

//设置cost

[cachesetObject:dataforKey:[NSStringstringWithFormat:@"%d",i]cost:i];

}

}

结果为:

2016-09-05 11:11:44.573 NSCachePractice[2433:70573] Data0 size:0

2016-09-05 11:11:44.573 NSCachePractice[2433:70573] data19 size:0

2016-09-05 11:11:44.574 NSCachePractice[2433:70573] Data20 size:0

2016-09-05 11:11:44.574 NSCachePractice[2433:70573] data21 size:0

2016-09-05 11:11:44.574 NSCachePractice[2433:70573] Data47 size:0

2016-09-05 11:11:44.574 NSCachePractice[2433:70573] Data48 size:213762

你可能感兴趣的:(iOS NSCache使用)