NSCache实现内存缓存

介绍

  • NSCache 是苹果提供的一个专门用来做缓存的类
  • 使用和 NSMutableDictionary 非常相似.但是是线程安全的
  • 取值

    • - (id)objectForKey:(id)key;
  • 设置对象,0成本

    • - (void)setObject:(id)obj forKey:(id)key;
  • 设置对象并指定成本

    • - (void)setObject:(id)obj forKey:(id)key cost:(NSUInteger)g;
  • 成本示例,以图片为例:

    • 方案一:缓存 100 张图片
    • 方案二:总缓存成本设定为 10M,以图片的 宽 * 高当作成本,图像像素。这样,无论缓存的多少张照片,只要像素值超过 10M,就会自动清理
    • 结论:在缓存图像时,使用成本,比单纯设置数量要科学!
  • 删除某个缓存的内容

    • - (void)removeObjectForKey:(id)key;
  • 删除全部

    • - (void)removeAllObjects;
    • 不能在 - (void)didReceiveMemoryWarning中调用此方法,否则NSCache就失效了

属性

  • @property NSUInteger totalCostLimit;

    • 缓存总成本
  • @property NSUInteger countLimit;

    • 缓存总数量
  • @property BOOL evictsObjectsWithDiscardedContent;

    • 是否自动清理缓存,默认是 YES

示例代码

 1 #import "ViewController.h"
 2 
 3 @interface ViewController () <NSCacheDelegate>
 4 
 5 @end
 6 
 7 @implementation ViewController {
 8     
 9     /// 全局缓存池
10     NSCache *_cache;
11 }
12 
13 - (void)viewDidLoad {
14     [super viewDidLoad];
15     
16     // 实例化缓存池
17     _cache = [[NSCache alloc] init];
18     
19     // 设置缓存成本 : 以最大的缓存个数为例(最多存5个对象)
20     _cache.countLimit = 5;
21     
22     // 遵守协议 : 有个唯一的代理方法,专门监听对象从cache里面移除
23     _cache.delegate = self;
24 }
25 
26 /// 添加对象
27 - (IBAction)addObj:(id)sender
28 {
29     for (NSInteger i = 0; i<10; i++) {
30         
31         NSString *key = [NSString stringWithFormat:@"hello_%zd",i];
32         
33         NSString *obj = [NSString stringWithFormat:@"hello_%zd",i];
34         NSLog(@"add %@",obj);
35         
36         [_cache setObject:obj forKey:key];
37     }
38 }
39 
40 /// 读取对象
41 - (IBAction)readObj:(id)sender
42 {
43     for (NSInteger i = 0; i<10; i++) {
44         
45         NSString *key = [NSString stringWithFormat:@"hello_%zd",i];
46         
47         // 存进去是什么,取出来应该就是什么
48         NSString *obj = [_cache objectForKey:key];
49         NSLog(@"read %@",obj);
50     }
51 }
52 
53 - (IBAction)removeAll:(id)sender
54 {
55     [_cache removeAllObjects];
56 }
57 
58 /// 这个代理方法,只在cache里面有对象被移除时调用
59 - (void)cache:(NSCache *)cache willEvictObject:(id)obj
60 {
61     // obj : 就是即将被移除的对象
62     NSLog(@"移除 %@",obj);
63 }
64 
65 /// NSCache的大坑 : 这个方法里面不能调用`removeAllObjects`;一旦调用了,cache就失效了
66 - (void)didReceiveMemoryWarning {
67     [super didReceiveMemoryWarning];
68     
69     [_cache removeAllObjects];
70 }
71 
72 @end
原文地址:https://www.cnblogs.com/panda1024/p/6277775.html