iOS 的檔案系統基於 Unix,每個 App 都在自己的沙盒中運作。本文整理兩種存取沙盒的方式,以及完整的檔案讀寫流程。
開啟終端機後輸入:
cd /Users/使用者名稱/Library/Application\ Support/iPhone\ Simulator/6.0/Applications/805D7CF0-5DBB-4FCD-9922-0D5C460F510E/
路徑結構為:
/Users/{主機使用者}/Library/Application Support/iPhone Simulator/{SDK 版本}/Applications/{App 唯一識別碼}/
其中 App 唯一識別碼就是實機上 bundle 的 UUID,每次重新安裝都會改變。進入後即可瀏覽該應用的各個目錄;若要對檔案做複製、刪除等操作,則需要 root 權限。
// Documents
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPaths = [paths objectAtIndex:0];
// Caches
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePaths = [paths1 objectAtIndex:0];
// Library
NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libraryPaths = [paths2 objectAtIndex:0];
參數說明:NSDocumentDirectory 指定要查找的目標目錄類型,NSUserDomainMask 指定從應用程式主目錄開始搜尋(也就是從 Applications 下對應的 App 資料夾找起),最後的 YES 表示希望取得所有找到項目的完整路徑。
[paths objectAtIndex:0] 這行只要記住就好:每個 App 資料夾裡只有一個 Documents,但 NSSearchPath 方法會回傳多個結果,取第一個即可。Caches 與 Library 同理。
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// 切換到待操作的目錄
[fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
// createFileAtPath: 參數依序為檔名、初始內容(可為 nil)、檔案屬性(可為 nil)
[fileManager createFileAtPath:@"fileName" contents:nil attributes:nil];
// 刪除
[fileManager removeItemAtPath:@"createdNewFile" error:nil];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"documentsDirecrtory:%@", documentsDirectory);
[fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
[fileManager createFileAtPath:@"fileone" contents:nil attributes:nil];
NSString *str = [documentsDirectory stringByAppendingPathComponent:@"fileone"];
NSLog(@"str:%@", str);
BOOL isExist = [fileManager fileExistsAtPath:str];
if (isExist) {
NSLog(@"文件存在");
} else {
NSLog(@"文件不存在");
}
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"fileone"];
NSLog(@"path:%@", path);
// 待寫入的資料
NSString *temp = @"Hello friend";
int data0 = 100000;
float data1 = 23.45f;
// 建立緩衝區並依序放入不同型別的資料
NSMutableData *writer = [[NSMutableData alloc] init];
[writer appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];
[writer appendBytes:&data0 length:sizeof(data0)];
[writer appendBytes:&data1 length:sizeof(data1)];
[writer writeToFile:path atomically:YES];
int gData0;
float gData1;
NSString *gData2;
NSData *reader = [NSData dataWithContentsOfFile:path];
gData2 = [[NSString alloc] initWithData:
[reader subdataWithRange:NSMakeRange(0, [temp length])]
encoding:NSUTF8StringEncoding]; // 第一段:字串
[reader getBytes:&gData0 range:NSMakeRange([temp length], sizeof(gData0))];
[reader getBytes:&gData1
range:NSMakeRange([temp length] + sizeof(gData0), sizeof(gData1))];
// NSMakeRange 代表資料範圍,getBytes:range: 從 reader 中取出指定範圍
NSLog(@"%@,%d,%f", gData2, gData0, gData1);
UInt8 b = 0;
// 從 mainBundle 取得檔案路徑
NSString *path1 = [[NSBundle mainBundle] pathForResource:@"key" ofType:@"txt"];
NSData *reader1 = [NSData dataWithContentsOfFile:path1];
int length = [reader1 length];
// 以 UTF8 解碼成字串
NSString *ges = [[NSString alloc] initWithData:
[reader1 subdataWithRange:NSMakeRange(0, length)]
encoding:NSUTF8StringEncoding];
NSLog(@"%@", ges);
NSLog(@"lenghth:%d", length);
// 逐位元組讀取
for (int i = 0; i < length; i++) {
[reader1 getBytes:&b range:NSMakeRange(i, sizeof(b))];
NSLog(@"----->data%d:%d", i, b);
}
讀檔時要先確認原檔案的格式是二進位還是純文字,兩者的解碼方式不同。上面範例同時示範了兩種:以 initWithData:encoding: 直接解成字串,以及用 getBytes:range: 逐位元組取出再自行組裝。
寫入順序決定讀取順序。這個範例把字串、int、float 依序寫進同一個檔案,讀取時必須用完全相同的順序與長度切分。實務上更穩妥的做法是改用 NSKeyedArchiver 序列化物件,或直接用 plist,讓格式自帶長度資訊。
不同目錄的特性不同。Documents 會被 iCloud/iTunes 備份,Caches 隨時可能被系統清除,tmp 在 App 未執行時也不保證存在。選擇存放位置時要先想清楚這份資料需不需要備份。
避免用 changeCurrentDirectoryPath。它改的是整個程式的當前工作目錄,屬於全域狀態,在多執行緒下容易出問題。建議一律用 stringByAppendingPathComponent: 組出絕對路徑,或改用 NSFileManager 的 URLsForDirectory:inDomains: 取得 NSURL 直接操作。