在模擬器上把資料寫進 App bundle 也許不會出錯,但換到真機就會失敗——因為真機環境下,App 在 Xcode 中的 Resources 相關目錄是唯讀的。任何寫入嘗試都會被系統拒絕,而且 App Store 審核也不允許你修改簽名過的 bundle 內容。
正確做法是在 App 第一次啟動時,把「需要日後修改並長期保存」的檔案從 bundle 複製到 Documents 目錄,之後所有讀寫都針對 Documents 裡那一份進行。
// 在 Documents 目錄中初始化地圖資料檔案
// 因為該目錄下的檔案可寫,而且可以持久保存
+(void)initDataFile {
NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
// 取得目標檔案路徑
sMapInfoInDocPath = [docPath stringByAppendingPathComponent:@"MapInfo.plist"];
NSFileManager *fm = [NSFileManager defaultManager];
// 如果目標檔案不存在,說明是 App 第一次運行
// 需要把可修改的資料檔從 bundle 拷貝到目標路徑
if (![fm fileExistsAtPath:sMapInfoInDocPath]) {
NSError *error = nil;
NSString *srcPath = [[NSBundle mainBundle] pathForResource:MAP_INFO_FILE ofType:@"plist"];
if (![fm copyItemAtPath:srcPath toPath:sMapInfoInDocPath error:&error]) {
CCLOG(@"ERR:copy file failed:%@", error);
}
}
}
刪掉 App 會連帶清掉這些檔案。 iTunes/Finder 備份與還原時,Documents 目錄通常會被涵蓋,但使用者手動刪除 App 後,該 App 在 Documents 底下的一切內容都會消失。若資料很重要,需要設計回復機制。
讀寫要考慮執行緒。 plist 的 NSDictionary writeToFile: 並非非同步,寫入大檔案時若放在主執行緒,容易讓 UI 卡住,建議移到背景佇列。
首次拷貝後就不再同步。 這個做法只保證「第一次啟動」拿到初始資料;後續若 App 升級帶了新版的預設 plist,你得自行比對版本並決定要不要覆蓋使用者既有的修改。