GitHub Demo: https://github.com/BaHui/NSCache
簡述
- 官方提供的緩存類造虎,用法與NSMutableDictionary的用法很相似,使用它來管理緩存贬派。
- 在系統內存很低時澎媒,會自動釋放一些對象;
- NSCache是線程安全的。
- NSCache的key只是做強引用戒努,不需要實現NSCopying協議。
官方接口
// 屬性
@property NSUInteger totalCostLimit; // 設置緩存數量
@property NSUInteger countLimit; // 設置最大花費量
@property BOOL evictsObjectsWithDiscardedContent;` // 是否移除不再被使用的對象
// 方法
- (nullable ObjectType)objectForKey:(KeyType)key;
- (void)setObject:(ObjectType)obj forKey:(KeyType)key; // 0 cost
- (void)setObject:(ObjectType)obj forKey:(KeyType)key cost:(NSUInteger)g;
- (void)removeObjectForKey:(KeyType)key;
- (void)removeAllObjects;
// 協議
@protocol NSCacheDelegate <NSObject>
@optional
- (void)cache:(NSCache *)cache willEvictObject:(id)obj;
@end
屬性設置
情景一: 僅設置緩存數量: countLimit
, 可用setObject: forKey:
加入對象
/** `countLimit` 設置緩存數量
* `setObject: forKey:`
* 當數量超出時, 默認會先移除最先添加的對象
*/
- (void)useCacheForOnlyCountLimit {
self.cache = [[NSCache alloc] init];
self.cache.countLimit = 5; // 設置緩存數量 <<
self.cache.delegate = self; // 設置代理對象
// 模擬存儲數據
for (NSInteger i = 1; i <= 8; i++) {
[self.cache setObject:@(i) forKey:@(i)];
}
}
- (void)cache:(NSCache *)cache willEvictObject:(id)obj {
NSLog(@"willEvictObject: %@", obj); // 輸出: 1 2 3
}
情景二: 僅設置最大花費量 totalCostLimit
, 可以setObject: forKey: cost:
加入對象
/** `totalCostLimit` 設置最大花費量
* `setObject: forKey: cost:`
* 當總花費量超出最大花費量, 默認會先移除最先添加的對象
*/
- (void)useCacheForOnlyTotalCostLimit {
self.cache = [[NSCache alloc] init];
self.cache.totalCostLimit = 10; // 設置緩存容量 <<
self.cache.delegate = self; // 設置代理對象
// 模擬存儲數據
for (NSInteger i = 1; i <= 8; i++) {
[self.cache setObject:@(i) forKey:@(i) cost:5];
}
}
- (void)cache:(NSCache *)cache willEvictObject:(id)obj {
NSLog(@"willEvictObject: %@", obj); // 1 2 3 4 5 6
}
情景三: 設置 緩存數量&最大花費量 countLimit & totalCostLimit
, 可用setObject: forKey:
& setObject: forKey: cost:
加入對象
/** `countLimit & totalCostLimit` 設置 緩存數量&最大花費量
* `setObject: forKey:` & `setObject: forKey: cost:`
* 當緩存數量大于最大緩存數量 或者 總花費量超出最大花費量, 默認會先移除最先添加的對象
*/
- (void)useCacheForCountAndTotalCostLimit {
self.cache = [[NSCache alloc] init];
self.cache.countLimit = 5; // 設置緩存數量 <<
self.cache.totalCostLimit = 20; // 設置緩存容量 <<
self.cache.delegate = self; // 設置代理對象
// 模擬存儲數據
for (NSInteger i = 1; i <= 8; i++) {
[self.cache setObject:@(i+100) forKey:@(i+100)];
[self.cache setObject:@(i) forKey:@(i) cost:1];
}
}
- (void)cache:(NSCache *)cache willEvictObject:(id)obj {
NSLog(@"willEvictObject: %@", obj);
// 101 1 102 2 103 3 104 4 105 5 106
}