缓存: NSCache

NSCache: 与NSMutableDictionary类似, 是一个可变集合, 通过key-value的方式存储数据

与NSMutableDictionary不同的是, NSCache存储数据时不会对key进行复制(copy), 而是强引用(strong), 所以NSCache存储数据使用key不需要实现NSCopying协议

  • 可以使用方法- (void)setObject:(ObjectType)obj forKey:(KeyType)key;进行存储数据
// 存储数据(key-value)
- (void)setObject:(ObjectType)obj forKey:(KeyType)key;
  • 通过方法- (nullable ObjectType)objectForKey:(KeyType)key;查看NSCache中存储的数据
// 取出key关联的value, 如果不存在, 返回nil
- (nullable ObjectType)objectForKey:(KeyType)key;
  • 示例代码
@interface ViewController ()

@property (nonatomic, strong) NSCache *cache;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _cache = [[NSCache alloc] init];
    
    UIImage *image = [UIImage imageNamed:@"1"];
    [_cache setObject:image forKey:@"image"];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"%@", [_cache objectForKey:@"image"]);
}

@end
  • 当点击屏幕时, 可以看到打印信息:
, {500, 710}
  • 可以调用- (void)removeObjectForKey:(KeyType)key;方法移除key关联的对象
- (void)removeObjectForKey:(KeyType)key;
  • 添加UIImage的分类, 实现下面的代码
#import "UIImage+Extension.h"
#import 

@implementation UIImage (Extension)
+ (void)load {
    Method originalMethod = class_getInstanceMethod([self class], NSSelectorFromString(@"dealloc"));
    Method swizzledMethod = class_getInstanceMethod([self class], @selector(bw_dealloc));
    // 交换方法
    method_exchangeImplementations(originalMethod, swizzledMethod);
}
- (void)bw_dealloc {
    [self bw_dealloc];
    NSLog(@"%s", __func__);
}
@end
  • 修改-touchesBegan:withEvent:中的代码
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [_cache removeObjectForKey:@"image"];
}
  • 再次点击屏幕, 可以看到image对象被释放
 -[UIImage(Extension) bw_dealloc]
  • NSCache有个delegate属性, 需要对象实现NSCacheDelegate协议, 协议中只有一个方法
// 当从cache中移除某个对象时调用
- (void)cache:(NSCache *)cache willEvictObject:(id)obj;
  • 我们可以修改测试代码, 如下
@interface ViewController () 

@property (nonatomic, strong) NSCache *cache;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _cache = [[NSCache alloc] init];
    _cache.delegate = self;
    UIImage *image = [UIImage imageNamed:@"1"];
    [_cache setObject:image forKey:@"image"];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_cache removeObjectForKey:@"image"];
}

#pragma mark - < NSCacheDelegate >
- (void)cache:(NSCache *)cache willEvictObject:(id)obj
{
    NSLog(@"移除 - %@", obj);
}
@end
  • 运行程序, 点击屏幕可以看到下面的打印, NSCache在移除image对象之前调用了cache: willEvictObject:方法
移除 - , {500, 710}
-[UIImage(Extension) bw_dealloc]

NSCache可以控制存储对象的数量

  • NSCache使用countLimit属性, 来控制可以存储对象的最大数量
// 可以存储的最大数量, 默认不限制
@property NSUInteger countLimit; 
  • 修改测试代码如下
@interface ViewController () 
@property (nonatomic, strong) NSCache *cache;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _cache = [[NSCache alloc] init];
    _cache.delegate = self;
    _cache.countLimit = 3;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    for (int i = 0; i < 5; i++) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"1.jpg" ofType:nil];
        NSData *data = [NSData dataWithContentsOfFile:path];
        [_cache setObject:data forKey:[@(i) debugDescription]];
    }
}

#pragma mark - < NSCacheDelegate >

- (void)cache:(NSCache *)cache willEvictObject:(id)obj {
    NSLog(@"移除 - %p", obj);
}
@end
  • 点击屏幕, 可以看到打印信息, 有两个NSData被移除了
移除 - 0x600002489920
移除 - 0x600002484d00

NSCache可以通过cost控制存储的对象数量

  • NSCache有一个属性totalCostLimit, 是用来控制存储对象的总cost, 当存储的对象总cost超过totalCostLimit, NSCache会移除部分的对象, 使总cost低于totalCostLimit
    • 默认情况下, totalCostLimit不做限制
  • NSCache中存储的每一个对象都有对应的cost, 而每个对象的cost是在存储到NSCache中时设置的
// 存储对象, 并设置对象对应的cost
- (void)setObject:(ObjectType)obj forKey:(KeyType)key cost:(NSUInteger)g;
// 存储对象, 并设置对象的cost为0
- (void)setObject:(ObjectType)obj forKey:(KeyType)key;
  • 修改测试代码如下
@interface ViewController () 
@property (nonatomic, strong) NSCache *cache;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _cache = [[NSCache alloc] init];
    _cache.delegate = self;
    _cache.totalCostLimit = 5;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    for (int i = 0; i < 10; i++) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"1.jpg" ofType:nil];
        NSData *data = [NSData dataWithContentsOfFile:path];
        [_cache setObject:data forKey:[@(i) debugDescription] cost:1];
    }
}

#pragma mark - < NSCacheDelegate >

- (void)cache:(NSCache *)cache willEvictObject:(id)obj {
    NSLog(@"移除 - %p", obj);
}

@end
  • 运行后点击屏幕, 可以看到下面的打印, 一共有五个对象被移除
移除 - 0x60000173d3c0
移除 - 0x60000173d3e0
移除 - 0x60000176e3c0
移除 - 0x60000176de80
移除 - 0x60000176de40

当内存不足时, NSCache会移除存储的内容

  • 内存不足时, NSCache会移除存储的对象, 可以使用下面的代码进行测试
@interface ViewController () 
@property (nonatomic, strong) NSCache *cache;
@property (nonatomic, assign) BOOL startDelete;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _cache = [[NSCache alloc] init];
    _cache.delegate = self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    for (int i = 0; i < 100000; i++) {
        if (_startDelete) return;       // 开始移除对象, 就不在添加新的对象到NSCache
        NSString *path = [[NSBundle mainBundle] pathForResource:@"1.jpg" ofType:nil];
        NSData *data = [NSData dataWithContentsOfFile:path];
        [_cache setObject:data forKey:[@(i) debugDescription]];
        NSLog(@"存储 - %p", data);
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    NSLog(@"内存不足");
}

#pragma mark - < NSCacheDelegate >

- (void)cache:(NSCache *)cache willEvictObject:(id)obj {
    _startDelete = YES;     // 开始移除对象
//    NSLog(@"移除 - %p", obj);
}

@end
  • 只要一直存, 就一定会出现内存不足的情况
缓存: NSCache_第1张图片
  • 修改- (void)cache:(NSCache *)cache willEvictObject:(id)obj中的代码
- (void)cache:(NSCache *)cache willEvictObject:(id)obj {
    _startDelete = YES;     // 开始移除对象
    NSLog(@"移除 - %p", obj);
}
  • 运行并点击屏幕, 可以看到内存不足时, 会移除对象
缓存: NSCache_第2张图片

注意: 内存不足时, NSCache会移除存储的内容, 所以一般只会缓存不重要的数据

NSCache的属性和方法

// 缓存的名称
@property (copy) NSString *name;
// 代理
@property (nullable, assign) id delegate;
// 取出key关联的value, 如果不存在, 返回nil
- (nullable ObjectType)objectForKey:(KeyType)key;
// 存储数据(key-value), cost的值默认为0
- (void)setObject:(ObjectType)obj forKey:(KeyType)key;
// 存储数据(key-value), 同时设置value对应的cost值
- (void)setObject:(ObjectType)obj forKey:(KeyType)key cost:(NSUInteger)g;
// 移除key关联的value
- (void)removeObjectForKey:(KeyType)key;
// 移除所有的缓存
- (void)removeAllObjects;
// 可以存储的Cost总大小, 默认不限制
@property NSUInteger totalCostLimit;
// 可以存储的最大数量, 默认不限制
@property NSUInteger countLimit;    

@property BOOL evictsObjectsWithDiscardedContent;

@end

@protocol NSCacheDelegate 
@optional
// 代理方法: NSCache中存储的对象, 将要从NSCache中移除时调用
- (void)cache:(NSCache *)cache willEvictObject:(id)obj;

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