iOS 的沙盒機制讓每個 App 只能在被允許的檔案系統區域中讀寫資料。非程式碼資源,例如圖片、圖示、聲音、屬性列表與文字檔,通常都儲存在沙盒內。

模擬器的沙盒位於使用者資料夾下的隱藏資源庫中。可透過終端顯示隱藏檔案,或直接前往以下路徑:
/Users/使用者名稱/Library/Application Support/iPhone Simulator/

進入後可看到各模擬器 App 的沙盒目錄。

一般沙盒包含三個主要目錄:


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [cachePaths objectAtIndex:0];
NSString *tmpDirectory = NSTemporaryDirectory();
可將陣列寫入 Documents 目錄:
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"testFile.txt"];
NSArray *array = @[@"內容", @"content"];
[array writeToFile:filePath atomically:YES];
讀取時可使用:
NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
NSLog(@"%@", array);

寫入後可在沙盒中看到檔案,內容通常以 plist 格式保存。透過這些 API,開發者可以完成基本的檔案持久化與讀寫操作。