iPhone 的沙盒(Sandbox)模型包含四個主要目錄,分別是 Documents、tmp、App(.app)、Library。永久資料一般存放在 Documents,而使用者偏好設定則透過 NSUserDefaults 保存。以下逐一說明各目錄用途與取得路徑的方法。
1. Documents 目錄:所有應用程式產生的資料檔案都應寫入此處,用於儲存使用者資料或其他需定期備份的資訊。
2. AppName.app 目錄:應用程式的程序包目錄,包含應用本身。由於應用經過簽名,運行時不可修改此目錄內容,否則可能導致程式無法啟動。
3. Library 目錄:包含兩個子目錄——
Preferences:存放偏好設定檔案,應使用 NSUserDefaults 類別存取,而非直接建立檔案。
Caches:存放應用專用的支援檔案,保存再次啟動時需要的信息。
4. tmp 目錄:存放臨時檔案,保存再次啟動時不需要的信息。
取得這些目錄路徑的常見方式:
// 家目錄 NSString *homeDir = NSHomeDirectory(); // Documents 目錄 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docDir = [paths objectAtIndex:0]; // Caches 目錄 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *cachesDir = [paths objectAtIndex:0]; // tmp 目錄 NSString *tmpDir = NSTemporaryDirectory(); // 取得程序包內資源檔案(如 apple.png)路徑 NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"apple" ofType:@"png"]; UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
其中 mainBundle 類別方法用於回傳代表應用程序包的物件。
檔案操作的常見範例:
NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:[self dataFilePath]]) {
// 建立指定路徑的目錄
[fm createDirectoryAtPath:[self dataFilePath] withIntermediateDirectories:YES attributes:nil error:nil];
// 取得某目錄下所有檔案名稱
NSArray *files = [fm subpathsAtPath:[self dataFilePath]];
// 讀取某個檔案
NSData *data = [fm contentsAtPath:[self dataFilePath]];
// 或者
NSData *data = [NSData dataWithContentOfPath:[self dataFilePath]];
}
另一種取得檔案路徑的簡便方式:先把檔案(例如 testFile.txt)放入 Resources 分組,再用以下程式碼取得路徑:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"testFile" ofType:@"txt"]; NSLog(@"data path: %@", filePath);
再以連接 SQLite 資料庫為例:
NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"myData" ofType:@"sqlite"];
if (sqlite3_open([dataPath UTF8String], &db) != SQLITE_OK) {
sqlite3_close(db);
NSLog(@"資料庫打開失敗");
} else {
NSLog(@"資料庫成功打開");
}
掌握這些路徑取得方法,就能在 iOS 開發中靈活地進行檔案讀寫與資源存取。