苹果官方的解释
An NSCache
object is a mutable collection that stores key-value pairs, similar to an object. The NSCache
class provides a programmatic interface to adding and removing objects and setting eviction policies based on the total cost and number of objects in the cache.(NSCache是系统提供的一种类似于集合(NSMutableDictionary)的缓存)
NSCache
objects differ from other mutable collections in a few ways:
-
The
NSCache
class incorporates various auto-eviction policies, which ensure that a cache doesn’t use too much of the system’s memory. If memory is needed by other applications, these policies remove some items from the cache, minimizing its memory footprint.(大意: NSCache具有自动删除的功能,以减少系统占用的内存) -
You can add, remove, and query items in the cache from different threads without having to lock the cache yourself. (大意:NSCache是线程安全的,不需要加线程锁)
-
Unlike an object, a cache does not copy the key objects that are put into it.(键对象不会像 NSMutableDictionary 中那样被复制。(键不需要实现 NSCopying 协议)。)
NSCache的属性以及方法介绍
@property NSUInteger totalCostLimit; //缓存的容量
@property NSUInteger countLimit;//缓存的个数
@property BOOL evictsObjectsWithDiscardedContent; //标识缓存是否自动舍弃那些内存已经被丢弃的对象(discardable-content object)默认是YES
delegate
//当要清理对象的时候调用
- (void)cache:(NSCache *)cache willEvictObject:(id)obj;
demo