NSCache

作者: 哥只是个菜鸟 | 来源:发表于2020-07-18 17:41 被阅读0次

SDWebImage里面使用了NSCache缓存数据,可见其缓存机制很好,用于存储临时数据

- (void)cache:(NSCache *)cache willEvictObject:(id)obj

代理方法,在删除时调用

  • APP进入后台时,自动清理数据
  • 超过最大存储限制时
  • 手动移除时
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self beginCache];
}

- (void)beginCache {
    for (int i = 0; i<10; i++) {
        NSString *obj = [NSString stringWithFormat:@"object--%d",i];
        [self.cache setObject:obj forKey:@(i) cost:1];
        NSLog(@"%@ cached",obj);
    }
}

#pragma mark - NSCacheDelegate

- (void)cache:(NSCache *)cache willEvictObject:(id)obj {
    
    NSLog(@"%@", [NSString stringWithFormat:@"%@ will be evict",obj]);
}


#pragma mark - Getter

- (NSCache *)cache {
    if (!_cache) {
        _cache = [NSCache new];
        _cache.totalCostLimit = 5;
        _cache.delegate = self;
    }
    return _cache;
}
2020-07-18 17:41:00.221505+0800 demo[59144:485192] object--0 cached
2020-07-18 17:41:00.221732+0800 demo[59144:485192] object--1 cached
2020-07-18 17:41:00.221876+0800 demo[59144:485192] object--2 cached
2020-07-18 17:41:00.221981+0800 demo[59144:485192] object--3 cached
2020-07-18 17:41:00.222082+0800 demo[59144:485192] object--4 cached
2020-07-18 17:41:00.222217+0800 demo[59144:485192] 删除object--0 will be evict
2020-07-18 17:41:00.222330+0800 demo[59144:485192] object--5 cached
2020-07-18 17:41:00.222452+0800 demo[59144:485192] 删除object--1 will be evict
2020-07-18 17:41:00.222539+0800 demo[59144:485192] object--6 cached
2020-07-18 17:41:00.222647+0800 demo[59144:485192] 删除object--2 will be evict
2020-07-18 17:41:00.222813+0800 demo[59144:485192] object--7 cached
2020-07-18 17:41:00.223120+0800 demo[59144:485192] 删除object--3 will be evict
2020-07-18 17:41:00.223421+0800 demo[59144:485192] object--8 cached
2020-07-18 17:41:00.223690+0800 demo[59144:485192] 删除object--4 will be evict
2020-07-18 17:41:00.223947+0800 demo[59144:485192] object--9 cached
2020-07-18 17:41:03.409134+0800 demo[59144:485192] EnterBackground
2020-07-18 17:41:03.461367+0800 demo[59144:485192] 删除object--5 will be evict
2020-07-18 17:41:03.461573+0800 demo[59144:485192] 删除object--6 will be evict
2020-07-18 17:41:03.461690+0800 demo[59144:485192] 删除object--7 will be evict
2020-07-18 17:41:03.461794+0800 demo[59144:485192] 删除object--8 will be evict
2020-07-18 17:41:03.462349+0800 demo[59144:485192] 删除object--9 will be evict

相关文章

网友评论

      本文标题:NSCache

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