美文网首页
说说NSCache缓存的原理

说说NSCache缓存的原理

作者: Adam_潜 | 来源:发表于2018-12-09 16:45 被阅读1次

https://www.jianshu.com/p/e850f8d120b0
iOS开发基础 | 被忽视和误解的NSCache
https://www.jianshu.com/p/e456b7b9f52d

  • NSCache是一个类似NSdictionary的可变集合
  • 提供了可以设置缓存树木与内存大小限制的方式
  • 保证了处理数据的线程安全
  • 缓存使用的key不需要是实现NSCopying的类
  • 当内存警告, 内部自动清理部分缓存数据
NSCache *cache = [[NSCache alloc] init];
cache.delegate = self;
 - (void)start:(id)sender {
    for (int i = 0; I < 1000; I++){
        NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"1" ofType:@"pptx"]];
[cache setObject:data forKey:[NSString stringWithFormat:@"image_%d", arc4random()];
    }
}

- (void)cache:(NSCache *)cache willEvictObject:(id)obj{
    NSLog(@"delete cache data");
}
static inline NSString *AFImageCacheKeyFromURLRequest(NSURLRequest *request){
    return [[request URL] absoluteString];
}

@interface AFImageCache:NSCache<AFImageCache>
@end
@implementation AFImageCache

- (UIImage *)cacheImageForRequest:(NSURLRequest *)request{
    switch([request cachePolicy]){
        case NSURLRequestReloadIgnoringCacheData:
        case NSURLRequestReloadIgnoreLocalAndRemoteCacheData:
    }
    return [self objectForKey:AfImageCacheFromURLRequest(request)];
}

- (void)cacheImage:(UIImage *)image forRequest:(NSURLRequest *)request{
    if (image && request]){
      [self setObject:image forKey:AfImageCacheForKeyFromURLRequest(request)];
    }
}

相关文章

网友评论

      本文标题:说说NSCache缓存的原理

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