您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 獲取各種檔案目錄路徑的方法

編輯:iOS 相關教學

iPhone 沙箱模型有四個資料夾,永久資料儲存一般放在什麼位置?取得模擬器路徑的簡單方式是什麼?本文將逐一說明。

四個主要目錄是:Documents、tmp、App、Library(透過 NSHomeDirectory() 取得家目錄)。手動儲存的檔案放在 Documents 裡,而 NSUserDefaults 儲存的資料則位於 Library 中。

各目錄的用途

1、Documents 目錄:應把所有應用程式的資料檔案寫入此目錄,用於儲存使用者資料或其他應定期備份的資訊。

2、AppName.app 目錄:應用程式的程式包目錄,包含應用程式本身。由於應用程式必須經過簽名,執行時不能修改此目錄的內容,否則可能導致程式無法啟動。

3、Library 目錄:其下有兩個子目錄——Caches 與 Preferences。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 dataWithContentsOfPath:[self dataFilePath]];
}

一種比較簡單的取檔方式

先把檔案(例如 testFile.txt)放在 Resources 分組下,然後這樣寫:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"testFile" ofType:@"txt"];
NSLog(@"data path: %@", filePath);

輸出的日誌中即可看到 testFile.txt 的路徑。再舉一個連接 SQLite 資料庫的例子:

NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"myData" ofType:@"sqlite"];
if (sqlite3_open([dataPath UTF8String], &db) != SQLITE_OK) {
    sqlite3_close(db);
    NSLog(@"資料庫打開失敗");
} else {
    NSLog(@"資料庫成功打開");
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved