plist 是 iOS 上最輕量的結構化資料格式之一。以下這段程式示範一個常見的模式:先確認 Caches 目錄中是否有該檔案,若沒有就從 App bundle 複製一份過去,最後再讀成 Dictionary。
// 1. 取得 Caches 目錄
NSArray *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDir = [cachePath objectAtIndex:0];
NSString *filePath = [cacheDir stringByAppendingPathComponent:@"version.plist"];
// 2. 若目標檔案不存在,則從 bundle 複製一份
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:filePath]) {
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:@"version.plist"];
NSError *error;
[fileManager copyItemAtPath:sourcePath toPath:filePath error:&error];
}
// 3. 讀取為字典
NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filePath];
App bundle 是唯讀的,程式無法直接寫入。因此凡是「需要修改」的設定檔,都必須先複製一份到沙盒的可寫目錄(Documents 或 Caches),之後所有的讀寫都針對那一份進行。
而選擇 Caches 而非 Documents 的理由是:Caches 裡的內容可以在裝置儲存空間不足時被系統清除,因此適合放「可重新產生」的資料,例如從 bundle 複製的預設設定檔;Documents 則受 iTunes/iCloud 備份保護,適合放使用者產生的資料。
使用 dictionaryWithContentsOfFile: 讀到的物件是不可變的。若後續需要修改內容,請改用 NSMutableDictionary:
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
另外,plist 只支援 NSString、NSNumber、NSData、NSDate、NSArray、NSDictionary 這幾種型別。若要存放自訂物件,必須先轉為上述型別(例如透過 NSKeyedArchiver 存成 NSData),否則 writeToFile: 會失敗。
最後,寫入時務必檢查回傳值並善用 atomically:YES,讓寫檔以「先寫暫存檔再取代」的方式進行,避免寫到一半斷電導致檔案損毀:
if ([dic writeToFile:filePath atomically:YES]) {
NSLog(@"寫入成功");
}