iOS 的沙盒機制是一種安全設計。每個 App 都被限制在各自的檔案系統空間中,彼此之間無法任意存取對方資料。所有非程式碼資源,例如 plist、文字檔、圖片、圖示與媒體檔案,都必須保存在這個沙盒區域內。
在 iPhone 的沙盒模型中,常見目錄包括 Documents、AppName.app、Library 與 tmp。
Documents 目錄通常用來保存使用者產生的資料,或需要定期備份的內容。例如記事本 App 中使用者輸入的文字、草稿或自訂設定,通常適合放在這裡。
這個目錄是 App 的程式包,包含應用程式本體。由於 App 經過簽名,執行階段不應修改這個目錄中的內容,否則可能導致 App 無法正常啟動。
Library 目錄下常見兩個子目錄:Caches 與 Preferences。
Preferences 通常用來保存偏好設定,建議透過 NSUserDefaults 存取,而不是手動建立檔案。
Caches 則適合保存可重新產生的快取資料,例如從伺服器下載後暫存的圖片或新聞內容。這類資料通常不需要備份。
tmp 目錄用來保存臨時檔案。這裡的資料在 App 結束後可能不再需要,因此不應存放重要資料。
在 Swift 中,可以透過 NSHomeDirectory、NSSearchPathForDirectoriesInDomains 與 NSTemporaryDirectory 等方法取得不同目錄。
let homeDir = NSHomeDirectory()
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentPath = paths.first
let cachePath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first
let tmpDir = NSTemporaryDirectory()
App 的資源通常打包在 main bundle 中。透過 NSBundle,可以取得圖片、媒體檔或其他資源的相對路徑。需要注意的是,若某個資源沒有被加入 Copy Bundle Resources,執行時可能無法取得。
let path = NSBundle.mainBundle().pathForResource("sample", ofType: "pcm")
若需要對沙盒中的檔案進行新增、讀取或檢查,可以使用 FileManager。常見操作包括判斷檔案是否存在、建立目錄、讀取內容與取得子路徑。
let fm = NSFileManager.defaultManager()
if !fm.fileExistsAtPath(path) {
fm.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil, error: nil)
}
掌握沙盒目錄的用途,不僅能讓資料保存更合理,也能減少 App 審核與備份行為上的問題。正確存放資料,是 iOS 開發中非常重要的一環。