NSCache

NSCache是由系统提供的类似集合(NSDictionary/NSMutableDictionary)的缓存。当NSCache检测到内存压力的时候,它会释放这些值清理空间。如果这些值可以在runtime过程中可以重新创建,那么NSCache是很好的选择(比如,网络下载图片,资源等),但是一些用户输入,有时效性的则用NSDictionary比较好,因为保存在NSCache中的数据会被释放。

相比于NSDictionary,NSCache的优点是:

  • NSCache在内存紧张时,会自动清理

  • NSCache并不拷贝(copy)键值,而是保留(retain)它

  • NSCache是线程安全的,不需要加锁(NSLock)保护

NSPurgeableData配合NSCache一起使用是非常好的选择。它可以选择的让NSCache在内存紧张时释放掉自己,在需要使用的时候,调用beginContentAccess,当使用结束后,调用endContentAccess告诉系统当前对象是可以被释放的。

- (void)downloadImageForURL:(NSURL *)url {
    NSPurgeableData *cacheData = [cache objectForKey:url];
    
    if (cacheData) {
        [cacheData beginContentAccess];
        //do something with the data
        [self useData: cacheData];
        
        [cacheData endContentAccess];
    } else {
        
        //download the image if the cache doesn't exist
        [ImageLoader loadImageWithURL: url, withCompletionHandler:^(NSData *data) {
            NSPurgeableData *purgeableData = [NSPurgeableData dataWithData: data];
            [cache setObject:purgeableData forKey: url];
            
            [self useData: cacheData];
            
            [purgeableData endContentAccess];
        }];
    }
}
原文地址:https://www.cnblogs.com/horo/p/6887846.html