Plist 是 iOS 上最簡單的輕量資料格式,適合存放小型設定或版本資訊。讀取時有兩個關鍵細節:一是檔案應該放在哪個目錄,二是首次啟動時如何把打包進 App 的初始檔案複製到可寫目錄。
NSArray *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDir = [cachePath objectAtIndex:0];
NSString *filePath = [cacheDir stringByAppendingPathComponent:@"version.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
// 若目標檔案不存在,就從 App 資源目錄複製一份過來
if (![fileManager fileExistsAtPath:filePath]) {
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:@"version.plist"];
NSError *error;
[fileManager copyItemAtPath:databasePathFromApp toPath:filePath error:&error];
}
NSDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
先用 NSSearchPathForDirectoriesInDomains 取得快取目錄路徑,拼出完整檔案路徑;接著檢查該檔案是否存在,若不存在就從 bundle 的資源目錄複製一份初始版本過來,最後用 dictionaryWithContentsOfFile: 一次讀進記憶體。
值得注意的是,App bundle 內的資源是唯讀的,因此「先複製到可寫目錄再操作」是必要步驟。如果這份資料只是唯讀的設定,可以直接從 bundle 讀取,不必複製;反之若程式會寫回內容,就一定要走複製流程,並養成檢查 NSError 的習慣,避免複製失敗卻沒有任何提示。