需要把物件(例如收藏清單)存到本地、下次開啟再讀回來時,NSKeyedArchiver / NSKeyedUnarchiver 是一對很好用的組合:archive 把物件樹序列化成 NSData,再用 writeToFile 落地;unarchive 則反向還原。下面以「收藏資料的讀取與更新」為例。
- (void)replaceCurrentViewData:(NSMutableArray *)array {
DWUser *loginUser = ((AppDelegate *)[UIApplication sharedApplication].delegate).appUser;
// 1. 從沙盒讀出既有資料
NSMutableDictionary *tempDic = [NSKeyedUnarchiver unarchiveObjectWithData:
[NSData dataWithContentsOfFile:[Utils applicationDocumentsDirectory:kCollectFilePath]]];
// 2. 以使用者名稱為 key,換成最新的收藏清單
[tempDic setObject:array forKey:loginUser.username];
// 3. 序列化後寫回檔案(atomically:YES 會先寫暫存檔再取代,避免寫到一半斷電)
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:tempDic];
[data writeToFile:[Utils applicationDocumentsDirectory:kCollectFilePath] atomically:YES];
}
這裡用「字典包字典」的結構,是為了讓多個帳號的收藏能共存於同一個檔案;以使用者名稱當 key,切換帳號時互不干擾。
不要自己拼 App 沙盒路徑(裡頭的 UUID 每次都不同),一律用 NSSearchPathForDirectoriesInDomains 取得 Documents 目錄:
+(NSString *)applicationDocumentsDirectory:(NSString *)filename {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return [basePath stringByAppendingPathComponent:filename];
}
NSCoding(encodeWithCoder: / initWithCoder:)的類別才能被 archive,自訂 model 別忘了這一步。