缓存: NSCache

2019-06-18  本文已影响0人  伯wen

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

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

// 存储数据(key-value)
- (void)setObject:(ObjectType)obj forKey:(KeyType)key;
// 取出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<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"%@", [_cache objectForKey:@"image"]);
}

@end
<UIImage: 0x6000001088c0>, {500, 710}
- (void)removeObjectForKey:(KeyType)key;
#import "UIImage+Extension.h"
#import <objc/runtime.h>

@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
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [_cache removeObjectForKey:@"image"];
}
 -[UIImage(Extension) bw_dealloc]
// 当从cache中移除某个对象时调用
- (void)cache:(NSCache *)cache willEvictObject:(id)obj;
@interface ViewController () <NSCacheDelegate>

@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<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_cache removeObjectForKey:@"image"];
}

#pragma mark - < NSCacheDelegate >
- (void)cache:(NSCache *)cache willEvictObject:(id)obj
{
    NSLog(@"移除 - %@", obj);
}
@end
移除 - <UIImage: 0x6000027bb090>, {500, 710}
-[UIImage(Extension) bw_dealloc]

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

// 可以存储的最大数量, 默认不限制
@property NSUInteger countLimit; 
@interface ViewController () <NSCacheDelegate>
@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<UITouch *> *)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
移除 - 0x600002489920
移除 - 0x600002484d00

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

// 存储对象, 并设置对象对应的cost
- (void)setObject:(ObjectType)obj forKey:(KeyType)key cost:(NSUInteger)g;
// 存储对象, 并设置对象的cost为0
- (void)setObject:(ObjectType)obj forKey:(KeyType)key;
@interface ViewController () <NSCacheDelegate>
@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<UITouch *> *)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会移除存储的内容

@interface ViewController () <NSCacheDelegate>
@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<UITouch *> *)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
- (void)cache:(NSCache *)cache willEvictObject:(id)obj {
    _startDelete = YES;     // 开始移除对象
    NSLog(@"移除 - %p", obj);
}

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

NSCache的属性和方法

// 缓存的名称
@property (copy) NSString *name;
// 代理
@property (nullable, assign) id<NSCacheDelegate> 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 <NSObject>
@optional
// 代理方法: NSCache中存储的对象, 将要从NSCache中移除时调用
- (void)cache:(NSCache *)cache willEvictObject:(id)obj;
上一篇 下一篇

猜你喜欢

热点阅读