App 開發中總會遇到「把數據存下來」的需求。對於關係結構清晰、數據量不大的輕量級場景,基於 Runtime 的歸檔方案是一個相當優雅的選擇——模型類只要聲明屬性,編碼解碼都能自動完成,不必像手写 NSCoding 那樣逐個字段 implement。
本文以一個完整的緩存管理類為例,說明如何設計一套「歸檔 + 過期判定 + 分文件存儲」的持久化解法。
這個 YHCacheManager 對每一類業務數據都提供四個能力:是否需要更新、寫入緩存、讀取緩存、清除緩存。同時引入「有效期」概念,不同數據用不同的過期時長,避免毫無察覺地讀到過期內容。
// YHCacheManager.h
#import <Foundation/Foundation.h>
#import "YHWorkGroup.h"
#import "YHABUserInfo.h"
#import "YHIMHandler.h"
#import "ConversationListHandler.h"
#import "YHThirdPModel.h"
@interface YHCacheManager : NSObject
+ (instancetype)shareInstance;
// 退出登錄時統一清理
- (void)clearCacheWhenLogout;
#pragma mark - 我的名片
- (BOOL)needUpdateMyCard;
- (void)cacheMyCard:(YHUserInfo *)userInfo;
- (YHUserInfo *)getCacheMyCard;
- (void)clearCacheMyCard;
#pragma mark - 工作圈動態列表
- (BOOL)needUpdateCacheWorkGroupDynamicList;
- (void)cacheWorkGroupDynamicList:(NSArray<YHWorkGroup *> *)listData;
- (NSArray<YHWorkGroup *> *)getCacheWorkGroupDynamiList;
- (void)clearCacheWorkGroupDynamiList;
// 按動態類型分開緩存
- (void)cacheWorkGroupDynamicList:(NSArray<YHWorkGroup *> *)listData
dynamicType:(NSInteger)dynamicType;
- (NSArray<YHWorkGroup *> *)getCacheWorkGroupDynamiListWithDynamicType:(NSInteger)dynamicType;
#pragma mark - 我的動態
- (BOOL)needUpdateCacheMyDynamicList;
- (void)cacheMyDynamciList:(NSArray<YHWorkGroup *> *)listData;
- (NSArray<YHWorkGroup *> *)getCacheMyDynamiList;
- (void)clearCacheMyDynamiList;
#pragma mark - 我的好友
- (BOOL)needUpdateCacheMyFriendsList;
- (void)cacheMyFriendsList:(NSArray<YHUserInfo *> *)listData;
- (NSArray<YHUserInfo *> *)getCacheMyFriendsList;
- (void)clearCacheMyFriendsList;
#pragma mark - 我的通訊錄
- (BOOL)needUpdateCacheMyABContactList;
- (void)cacheMyABContactList:(NSArray<YHABUserInfo *> *)listData;
- (NSArray<YHABUserInfo *> *)getCacheMyABContactList;
- (void)clearCacheMyABContactList;
#pragma mark - 大咖列表
- (BOOL)needUpdateBigNameList;
- (void)cacheBigNameList:(NSArray<YHUserInfo *> *)listData;
- (NSArray<YHUserInfo *> *)getCacheBigNameList;
- (void)clearCacheBigNameList;
#pragma mark - 我的訪客
- (BOOL)needUpdateMyVisitorsList;
- (void)cacheMyVisitorsList:(NSArray<YHUserInfo *> *)listData;
- (NSArray<YHUserInfo *> *)getCacheMyVisitorsList;
- (void)clearCacheMyVisitorsList;
#pragma mark - 新的好友
- (BOOL)needUpdateNewFriendsList;
- (void)cacheNewFriendsList:(NSArray<YHUserInfo *> *)listData;
- (NSArray<YHUserInfo *> *)getCacheNewFriendsList;
- (void)clearCacheNewFriendsList;
#pragma mark - 行業職位列表
- (BOOL)needUpdateIndustryList;
- (void)cacheIndustryList:(NSArray<NSDictionary *> *)listData;
- (NSArray<NSDictionary *> *)getCacheIndustryList;
- (void)clearCacheIndustryList;
#pragma mark - 評論推送
- (BOOL)needUpdateNotiCommentSingleton;
- (void)cacheNotiCommentSingleton:(YHIMHandler *)singleton;
- (YHIMHandler *)getCacheNotiCommentSingleton;
- (void)clearCacheNotiCommentSingleton;
#pragma mark - 會話列表
- (BOOL)needUpdateConversationSingleton;
- (void)cacheConversationSingleton:(ConversationListHandler *)singleton;
- (ConversationListHandler *)getCacheConversationSingleton;
- (void)clearCacheConversationSingleton;
#pragma mark - 第三方賬號
- (void)cacheThirdPartyAccount:(YHThirdPModel *)dict;
- (NSMutableDictionary<NSString *, YHThirdPModel *> *)getCacheThirdPartyAccountDict;
- (void)clearCacheThirdPartyAccountDict;
@end
首先是有效期配置。每類數據一個常量,0 表示永不過期:
static long const kMyCardValidDuration = 0; static long const kWorkgroupDynamicListValidDuration = 3600 * 1; static long const kMyDynamicListValidDuration = 3600 * 1; static long const kMyFriendsListValidDuration = 60; static long const kMyABContactListValidDuration = 0; static long const kBigNameListValidDuration = 0; static long const kMyVisitorsListValidDuration = 0; static long const kNewFriendsListValidDuration = 0; static long const kIndustryListValidDuration = 3600 * 24 * 7; static long const kNotiCommentSingletonValidDuration = 3600 * 24 * 30; static long const kConversationSingletonValidDuration = 0;
過期判定與時間戳寫入這兩個私有方法,是整套機制的基礎:
// 是否已過期。YES: 過期 NO: 有效
- (BOOL)isExpiredWithCacheKey:(NSString *)cacheKey validDuration:(long)validDuration {
NSInteger ts = [[NSUserDefaults standardUserDefaults] integerForKey:cacheKey];
if (ts == 0) {
ts = [[NSDate date] timeIntervalSince1970];
[[NSUserDefaults standardUserDefaults] setObject:@(ts) forKey:cacheKey];
}
NSDate *oDate = [NSDate dateWithTimeIntervalSince1970:ts];
NSTimeInterval distance = [[NSDate date] timeIntervalSinceDate:oDate];
return distance > validDuration;
}
// 記錄本次緩存時間
- (void)cacheCurrentDateWithKey:(NSString *)cacheDateKey {
if (!cacheDateKey) return;
NSTimeInterval interval = [[NSDate date] timeIntervalSince1970];
[[NSUserDefaults standardUserDefaults] setObject:@(interval) forKey:cacheDateKey];
}
以「我的名片」為例,一組完整的 CRUD 長這樣:
- (BOOL)needUpdateMyCard {
return (!self.cacheUserInfo || [self isMyCardExpired]) ? YES : NO;
}
- (void)cacheMyCard:(YHUserInfo *)userInfo {
if (!userInfo) return;
self.cacheUserInfo = userInfo;
YHSERIALIZE_ARCHIVE(self.cacheUserInfo, kArchiveKeyMyCard, [self cacheMyCardFilePath]);
[self cacheCurrentDateWithKey:kcacheDateMyCard];
}
- (YHUserInfo *)getCacheMyCard {
YHSERIALIZE_UNARCHIVE(self.cacheUserInfo, kArchiveKeyMyCard, [self cacheMyCardFilePath]);
return self.cacheUserInfo;
}
- (void)clearCacheMyCard {
[self deleteFileAtPath:[self cacheMyCardFilePath]];
}
其餘十來類數據結構完全同構,只是 key 與文件路徑不同。
把每一類數據寫入獨立文件,是這個設計裡最值得借鑑的一點。好處很直接:清理某類數據只需刪一個文件,不必解析整個大檔案;同時避免多類數據擠在同一文件裡導致的讀寫放大。
- (NSString *)cachePath {
NSString *doc = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
NSUserDomainMask, YES)[0];
return [doc stringByAppendingPathComponent:[[NSProcessInfo processInfo] processName]];
}
- (NSString *)cacheMyCardFilePath {
return [[self cachePath] stringByAppendingPathComponent:@"myCard"];
}
- (NSString *)cacheWorkGroupListFilePath {
return [[self cachePath] stringByAppendingPathComponent:@"wgdynList"];
}
- (NSString *)cacheWorkGroupListFilePathWithDynamicType:(NSInteger)dynamicType {
return [[self cachePath] stringByAppendingPathComponent:
[NSString stringWithFormat:@"wgdynList%@", [@(dynamicType) stringValue]]];
}
// 其餘:mydynList / myfriendsList / myABContactList / bigNameList /
// myVisitorsList / newFriendsList / industryList /
// notiCommentSingleton / thirdPartyAccount ...
- (BOOL)deleteFileAtPath:(NSString *)filePath {
if (!filePath || filePath.length == 0) return NO;
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
DDLog(@"delete file error, %@ is not exist!", filePath);
return NO;
}
NSError *removeErr = nil;
if (![[NSFileManager defaultManager] removeItemAtPath:filePath error:&removeErr]) {
DDLog(@"delete file failed! %@", removeErr);
return NO;
}
return YES;
}
會話列表放在 Document 目錄而非 Cache 目錄,因為它需要在系統清理緩存時保留下來;其餘數據則可以隨系統回收。
第三方賬號緩存用平台名做 key,便於按平台獨立更新:
- (void)cacheThirdPartyAccount:(YHThirdPModel *)model {
if (!model) { DDLog(@"緩存的 model 為 nil"); return; }
// key 值與友盟 platform 名保持一致
NSString *platformName = @"tPAccount";
if (model.platformType == UMSocialPlatformType_QQ) platformName = @"qq";
NSMutableDictionary *dictCache = [self getCacheThirdPartyAccountDict];
if (dictCache) {
[dictCache setObject:model forKey:platformName];
} else {
NSMutableDictionary *dictWriteToF = [NSMutableDictionary new];
[dictWriteToF setObject:model forKey:platformName];
self.thirdPartyDict = dictWriteToF;
YHSERIALIZE_ARCHIVE(self.thirdPartyDict, kArchiveKeyCacheThirdPartyDict,
[self cacheThirdPartyAccountFilePath]);
[self cacheCurrentDateWithKey:kcacheDateThirdPartyDict];
}
}
清除緩存時,除了刪文件,記得把內存中的單例數據也一并清空,否則本次運行期內仍會讀到髒數據:
- (void)clearCacheNotiCommentSingleton {
[self deleteFileAtPath:[self cacheNotiCommentSingletonFilePath]];
[[YHIMHandler sharedInstance].dataArray removeAllObjects];
[YHIMHandler sharedInstance].totalBadge = 0;
}
總結一下這套方案的適用邊界:數據結構固定、單條不大、總量可控時,Runtime 歸檔開發效率極高;但如果是海量數據或需要複雜查詢,仍然應該果斷切換到 Core Data 或 SQLite。