NSCache相关查了一些资料,没有找到核心思想的阐述,自己试验了下,验证了NSCache使用了LRU缓存算法策略。
在这里不再说明NSCache一些调用API和代理回调相关基础知识,直接贴代码。
NSCache *cache = [NSCache new];
cache.delegate=self;
cache.countLimit = 5;
[cache setObject:@"1" forKey:@"1"];
[cache setObject:@"2" forKey:@"2"];
[cache setObject:@"3" forKey:@"3"];
[cache setObject:@"4" forKey:@"4"];
[cache setObject:@"5" forKey:@"5"];
[cache setObject:@"6" forKey:@"6"];
sleep(2);
[cache objectForKey:@"2"];
[cache setObject:@"7"forKey:@"7"];
sleep(2);
[cache setObject:@"8"forKey:@"8"];
//当缓存中的一个对象即将被删除时会回调该方法
- (void)cache:(NSCache*)cachewillEvictObject:(id)obj {
NSLog(@"Remove Object %@", obj);
}
以下是打印:
2020-07-02 17:05:17.344311+0800 int[34442:1168078] Remove Object 1
2020-07-02 17:05:19.345237+0800 int[34442:1168078] Remove Object 3
2020-07-02 17:05:21.345610+0800 int[34442:1168078] Remove Object 4
网友评论