官方對自己的描述是:一個簡單、線程安全的 key-value 儲存。它原生支援 NSString、UIImage / NSImage 與 NSData,同時也能存任何實作 <NSCoding> 的物件;每筆資料都有過期時間,預設一天。
整個框架只有 EGOCache.h 與 EGOCache.m 兩個檔案,API 看一眼就會用。值得注意的是它只提供磁碟緩存,沒有內存緩存;此外附了兩個實用方法:
- (void)clearCache; // 清空全部緩存 - (BOOL)hasCacheForKey:(NSString* __nonnull)key; // 判斷某個 key 是否存在
在 Podfile 補上一行,然後執行 pod update:
pod 'EGOCache'
// 儲存字串
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]]];
// 儲存圖片
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
NSData *saveData = [NSData data];
[[EGOCache globalCache] setData:saveData
forKey:[NSString stringWithFormat:@"EGOImageLoader-%lu", (unsigned long)[@"SaveData" hash]]
withTimeoutInterval:24 * 60 * 60];
UIImage *getSaveData = [[EGOCache globalCache] dataForKey:
[NSString stringWithFormat:@"EGOImageLoader-%lu", (unsigned long)[@"SaveData" hash]]];
用起來跟 NSDictionary 幾乎一樣——這很合理,因為它本來就是 key-value 設計,只是多了一層「過期時間」與「落磁碟」。
原始碼裡預設值寫得很直白:
[self setDefaultTimeoutInterval:86400]; // 86400 = 24 * 60 * 60,剛好一天
能自訂過期時間的最大好處,是可以「光靠寫入時的參數」來管理不同資料的生命週期,不必另外維護一套清理邏輯。
先別急著看答案,如果換你來寫,大概會想到這幾招:開一個計時器定期掃描、寫個 while 迴圈輪詢、或者每次讀取時順手判斷有沒有過期。
仔細一想,前兩種都在為一件小事付出資源成本;第三種則有個明顯破綻——如果一直沒人讀,緩存只會無限膨脹。所以三招都被淘汰了。
答案藏在 initWithCacheDirectory::每次建立 EGOCache 實例時,它會遍歷 plist 中記錄的所有緩存項,把每筆的到期時間與「現在」比一次,凡是已過期的就刪掉對應檔案,並把該 key 從 plist 移除。
// 1. 讀取緩存資訊
_cacheInfo = [[NSDictionary dictionaryWithContentsOfFile:cachePathForKey(_directory, @"EGOCache.plist")] mutableCopy];
if (!_cacheInfo) {
_cacheInfo = [[NSMutableDictionary alloc] init];
}
// 2. 取得當前時間
NSTimeInterval now = [[NSDate date] timeIntervalSinceReferenceDate];
// 3. 準備一個陣列存放過期 key
NSMutableArray *removedKeys = [[NSMutableArray alloc] init];
// 4. 逐一比對到期時間
for (NSString *key in _cacheInfo) {
if ([_cacheInfo[key] timeIntervalSinceReferenceDate] <= now) {
[[NSFileManager defaultManager] removeItemAtPath:cachePathForKey(_directory, key) error:NULL];
[removedKeys addObject:key];
}
}
// 5. 把過期 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;
}
「啟動時批次清理 + 讀取時即時複核」這兩段搭配起來,才算把過期這件事處理乾淨。這套思路不限於緩存,任何帶 TTL 的本地資料都能借鏡。