iOS 的檔案系統對 App 是封閉的。每個應用只能在自己的沙盒裡存取資料,看不到別人的,也出不去。理解這套機制,是處理資料庫、快取、檔案分享之前的基本功。
iOS 應用只能訪問為其建立的專屬區域,其中的非程式碼資源——圖片、plist、bundle、nib 檔等——都存在這裡,這塊區域就稱為沙盒(Sandbox)。
三條規則:
第三點尤其要注意資料庫。在自己電腦上除錯時能開啟的 db 檔,裝到真機上就會失敗,因為真機遵循沙盒限制。正確做法是首次啟動時把預設資料庫從 Bundle 拷貝到沙盒的 Documents 目錄,之後所有讀寫都針對沙盒中的副本。
NSLog(@"沙盒路徑:%@", NSHomeDirectory());
輸出的路徑中,最後一段是裝置的應用程式識別碼:
/Users/apple/Library/Application Support/iPhone Simulator/6.1/Applications/****-****-****-****
打開 Finder,前往 → 前往檔案夾(或按 command+shift+G),貼上路徑即可進入。
打開 Finder,前往並按住 option 鍵,選單中才會出現「資源庫」。

依序進入 Application Support → iPhone Simulator → 對應的模擬器版本,就能看到各個應用的沙盒目錄。

選中其中任一項,即可看到以程式名稱命名的 .app 檔案。

沙盒預設包含 Documents、Library、tmp 三個目錄,以及那個帶圖示的 .app 檔案。
| 目錄 | 用途 | 是否被 iCloud/iTunes 備份 |
|---|---|---|
| Documents | 存放應用的正式資料,如資料庫、使用者產生的檔案 | 會備份 |
| Library | 存放預設設定與狀態資訊 | 會備份 |
| Library/Caches | 存放快取,App 退出時不刪除 | 不會備份 |
| tmp | 存放臨時檔案 | 不會備份 |
選用哪個目錄有明確判準:能重新產生的放 Caches 或 tmp,不能重生的放 Documents。把可重生的巨大快取塞進 Documents,會讓用戶的 iCloud 空間迅速爆滿。
至於 .app 檔案,選中後顯示包裹內容,就能看到圖示、nib、plist 等打包資源。這個目錄是唯讀的,執行期無法寫入。

以下在 Documents 下建立一個 plist,寫入圖片或其他檔案的邏輯完全一樣。
// 取得 Documents 目錄
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES) objectAtIndex:0];
// 拼出完整路徑
NSString *plistPath = [rootPath stringByAppendingPathComponent:@"new.plist"];
// 序列化並寫入
NSString *error;
id plist = [NSPropertyListSerialization dataFromPropertyList:@"OK"
format:NSPropertyListXMLFormat_v1_0
errorDescription:&error];
if (plist) {
NSLog(@"No error creating XML data.");
[plist writeToFile:plistPath atomically:YES];
} else {
NSLog(@"%@", error);
[error release];
}
執行後 Documents 下會多出一個 new.plist。

打開可以看到其中存著一個值 OK。想存陣列或字典,只要把上面的 "OK" 換成對應的 id 物件即可。

實務上更常用的寫法是直接對 NSDictionary / NSArray 呼叫 writeToFile:atomically:,plist 序列化會自動完成,不必手動走 NSPropertyListSerialization。
下面把 public.xml 拷貝到 Documents。其他檔案同理,只要副檔名對應即可。資料庫檔尤其必須走這一步,因為 .app 內是唯讀的。
// 取得 Documents 路徑
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES) lastObject];
// 目標路徑
NSString *xmlSandBoxPath = [documentsPath stringByAppendingPathComponent:@"public.xml"];
NSFileManager *fileManager = [NSFileManager defaultManager];
// 先檢查是否已存在,避免每次啟動都覆蓋使用者資料
BOOL isExisting = [fileManager fileExistsAtPath:xmlSandBoxPath];
if (!isExisting) {
// 從 Bundle 取來源檔案
NSString *xmlFilePath = [[NSBundle mainBundle] pathForResource:@"public" ofType:@"xml"];
NSError *err;
[fileManager copyItemAtPath:xmlFilePath toPath:xmlSandBoxPath error:&err];
if (err) {
NSLog(@"拷貝失敗:%@", err);
}
}
執行後 Documents 下就有這個檔案了。

用 NSFileManager 而非 NSData 讀寫大檔。一次把整個檔案載入記憶體,遇到幾十 MB 的檔案會直接吃爆記憶體。
路徑取得用 API 而非硬編碼。NSHomeDirectory() 加上手動拼接看似可行,但沙盒路徑中的 UUID 每次安裝都會變,硬編碼的路徑在真機上必然失效。
注意 ARC 與 MRC 的差異。本文部分範例寫於 MRC 時代(如 [error release]),在 ARC 專案中請刪除所有手動 release 呼叫。