美文网首页
iOS NSCache使用

iOS NSCache使用

作者: 红烧大鸡腿 | 来源:发表于2016-09-05 11:31 被阅读183次

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使用

    http://www.15yan.com/story/45toOUzFGlr/ NSCache可以设置数量限制,通...

  • NSCache内存缓存

    NSCache 基本使用 NSCache缓存类介绍 NSCache源码

  • 了解NSCache的基本使用

    NSCache是专门用来进行缓存处理的, NSCache简单介绍:NSCache是苹果官方提供的缓存类,具体使用和...

  • 我们应该使用的NSCache(链接)

    我们应该使用的NSCache

  • NSCache

    NSCache类 NSCacheDelegate协议 一、NSCache特点 1、使用方便,类似字典 2、线程安全...

  • iOS开发之NSCache

    NSCache的特点 NSCache是苹果推出专门用来处理内存缓存的类;NSCache默认是线程安全的,在使用的时...

  • iOS -- NSCache

    NSCache 存储的对象,在app进入background时所有对象会被清除。以下是小实验。 NSPurgeab...

  • iOS NSCache

    NSCache 概述 NSCache 是一个类似 NSDictionary一个可变的集合。 提供了可设置缓存的数目...

  • NSCache简介

    NSCache苹果提供的一套缓存机制,当今主流的SDWebImage正是使用了NSCache进行缓存 相对比使用N...

  • NSCache

    NSCache简单说明 1.NSCache是苹果官方提供的缓存类,具体使用和NSMutableDictionary...

网友评论

      本文标题:iOS NSCache使用

      本文链接:https://www.haomeiwen.com/subject/hddrettx.html