官方描述是:
EGOCache is a simple, thread-safe key value cache store. It has native support for NSString, UI/NSImage, and NSData, but can store anything that implements <NSCoding>. All cached items expire after the timeout, which by default, is one day.
翻譯過來:EGOCache 是一個簡單、執行緒安全的 key-value 緩存框架,原生支援 NSString、UIImage/NSImage 與 NSData,也能儲存任何實作 <NSCoding> 的類別,並可設定過期時間,預設一天。
整個框架只有 EGOCache.h 與 EGOCache.m 兩個檔案,研究一下頭檔中的方法就能快速上手。它只提供磁碟緩存,沒有內存緩存,同時提供了清理與檢查的方法:
- (void)clearCache; - (BOOL)hasCacheForKey:(NSString * __nonnull)key;
在 Podfile 中加入:
pod 'EGOCache'
然後執行:
$ pod update
// 儲存
NSString *saveString = @"把我保存起來吧";
[[EGOCache globalCache] setString:saveString
forKey:[NSString stringWithFormat:@"EGOImageLoader-%lu", (unsigned long)[saveString hash]]
withTimeoutInterval:24 * 60 * 60];
// 讀取
NSString *getSaveString = [[EGOCache globalCache]
stringForKey:[NSString stringWithFormat:@"EGOImageLoader-%lu", (unsigned long)[@"SaveString" hash]]];
是不是很像 NSDictionary?沒錯,它就是一個 key-value 的緩存框架。
// 儲存
UIImage *saveImage = [UIImage imageNamed:@"iOSDevTip"];
[[EGOCache globalCache] setImage:saveImage
forKey:[NSString stringWithFormat:@"EGOImageLoader-%lu", (unsigned long)[@"SaveImage" hash]]
withTimeoutInterval:24 * 60 * 60];
// 讀取
UIImage *getSaveImage = [[EGOCache globalCache]
imageForKey:[NSString stringWithFormat:@"EGOImageLoader-%lu", (unsigned long)[@"SaveImage" hash]]];
// 儲存
NSData *saveData = [NSData data];
[[EGOCache globalCache] setData:saveData
forKey:[NSString stringWithFormat:@"EGOImageLoader-%lu", (unsigned long)[@"SaveData" hash]]
withTimeoutInterval:24 * 60 * 60];
// 讀取
NSData *getSaveData = [[EGOCache globalCache]
dataForKey:[NSString stringWithFormat:@"EGOImageLoader-%lu", (unsigned long)[@"SaveData" hash]]];
預設時間在源碼中是這樣設定的:
[self setDefaultTimeoutInterval:86400]; // 86400 = 24 * 60 * 60,剛好一天
可設定過期時間的最大好處,是能定時淘汰舊資料、方便管理緩存體積。於是兩個問題出現了:
公司裡主管常舉的例子是:新人遇到問題只會抱怨、把問題丟給長官;成長之後,不只把問題丟出來,還附上自己的解法。既然提出了問題,先想想自己會怎麼做:
仔細想就會發現弊端:為了小小的過期時間開輪詢計時器是資源浪費;while 迴圈更糟;只在讀取時判斷的話,若一直沒人讀取,緩存會無限膨脹。三種都被排除了。
查看源碼會發現,在 initWithCacheDirectory: 中,每次初始化實例時會遍歷 plist 裡所有既存緩存項,把每項的過期時間與當前時間比對,過期的就刪除檔案並移除 plist 中對應的 key 記錄。
讀取緩存資訊:
_cacheInfo = [[NSDictionary dictionaryWithContentsOfFile:cachePathForKey(_directory, @"EGOCache.plist")] mutableCopy];
if (!_cacheInfo) {
_cacheInfo = [[NSMutableDictionary alloc] init];
}
取得當前時間:
NSTimeInterval now = [[NSDate date] timeIntervalSinceReferenceDate];
準備收集過期的 key:
NSMutableArray *removedKeys = [[NSMutableArray alloc] init];
遍歷並判斷:
for (NSString *key in _cacheInfo) {
// 過期時間早於(或等於)當前時間
if ([_cacheInfo[key] timeIntervalSinceReferenceDate] <= now) {
[[NSFileManager defaultManager] removeItemAtPath:cachePathForKey(_directory, key) error:NULL];
[removedKeys addObject:key];
}
}
最後把過期 key 從 plist 的記錄中移除:
[_cacheInfo removeObjectsForKeys:removedKeys];
把清理動作綁在「初始化」這個時機,是相當聰明的取捨——不必額外常駐資源,又能自然收斂。
EGOCache 是單例,也就是整個 App 生命週期中只初始化一次:
+ (instancetype)globalCache {
static id instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[[self class] alloc] init];
});
return instance;
}
這帶來一個情境問題:使用者打開 App 時初始化並清理過一次;若某些項目是在初始化「之後」才過期,這次清理就抓不到它們,讀取時仍會拿到已過期的資料。
繼續看源碼會發現,EGOCache 在讀取時又做了一次判斷:先確認項目存在,取出後再比對時間是否已過期。
- (BOOL)hasCacheForKey:(NSString *)key {
// 取出初始化時尚未過期的項目
NSDate *date = [self dateForKey:key];
if (date == nil) return NO;
// 判斷目前是否已過期
if ([date timeIntervalSinceReferenceDate] < CFAbsoluteTimeGetCurrent()) return NO;
return [[NSFileManager defaultManager] fileExistsAtPath:cachePathForKey(_directory, key)];
}
- (NSDate *)dateForKey:(NSString *)key {
__block NSDate *date = nil;
dispatch_sync(_frozenCacheInfoQueue, ^{
date = (self.frozenCacheInfo)[key];
});
return date;
}
「初始化時批量清理 + 讀取時單項複核」這兩層設計,正是這個框架值得借鏡的地方。日後遇到類似的本地緩存需求,完全可以沿用同樣的思路:把成本高的全域掃描放在啟動階段,把即時性判斷放在讀取路徑上。