您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

iOS 開發:取得檔案路徑的四種常見寫法

編輯:iOS 7 技巧

在 iOS 開發中,讀寫檔案前得先拿到正確的路徑。沙盒有幾個標準目錄,用對 API 才能避免路徑寫死導致的相容問題。以下整理四種常用寫法。

一、取得 Documents 目錄並組出完整路徑

這是最通用的做法,透過系統 API 取得文件目錄,再拼接檔名:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:filename];

二、用巨集直接組出 Documents 下的路徑

若路徑結構固定,用巨集封裝能讓程式碼更精簡:

#define ABS_FILE_PATH(FILE_NAME) [NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(), FILE_NAME]

三、讀取 App Bundle 內建資源

打包進 App 的檔案放在主 Bundle 的資源目錄中:

#define PACKAGE_FILE_PATH(FILE_NAME) [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:FILE_NAME]

四、以資源名稱與副檔名查詢路徑

知道檔名與類型時,用這個方法最直覺:

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"fileType (txt...html..)"];

選用建議

要讀寫使用者產生的資料(例如資料庫、下載檔案)走 Documents;要讀取 App 內建的靜態資源則走 Bundle。兩者不可混用,因為 Bundle 目錄在簽章後是唯讀的。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved