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

benbenxiongyuan發表於2013-09-02

iphone沙箱模型的有四個資料夾,分別是什麼,永久資料儲存一般放在什麼位置,得到模擬器的路徑的簡單方式是什麼.

documents,tmp,app,Library。

(NSHomeDirectory()),

手動儲存的檔案在documents檔案裡

Nsuserdefaults儲存的檔案在tmp資料夾裡


1、Documents 目錄:您應該將所有de應用程式資料檔案寫入到這個目錄下。這個目錄用於儲存使用者資料或其它應該定期備份息。

2、AppName.app 目錄:這是應用程式程式包目錄,包含應用程式身。由於應用程式必須經過簽名,所以您在執行時不能對這個目錄中內容進行修改,否則可能會使應用程式無法啟動。

3、Library 目錄:這個目錄下有兩個子目錄:Caches 和 Preferences
Preferences 目錄:包含應用程式偏好設定檔案。您不應該直接建立偏好設定檔案,而是應該使用NSUserDefaults類來取得和設定應用程式偏好.
Caches 目錄:用於存放應用程式專用支援檔案,儲存應用程式再次啟動過程中需要資訊。

4、tmp 目錄:這個目錄用於存放臨時檔案,儲存應用程式再次啟動過程中不需要資訊。


獲取這些目錄路徑方法:
1,獲取家目錄路徑函式:
NSString *homeDir = NSHomeDirectory();
2,獲取Documents目錄路徑方法:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
3,獲取Caches目錄路徑方法:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
4,獲取tmp目錄路徑方法:
NSString *tmpDir = NSTemporaryDirectory();
5,獲取應用程式程式包中資原始檔路徑方法:
例如獲取程式包中一個圖片資源(apple.png)路徑方法:
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@”apple” ofType:@”png”];
UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
程式碼中mainBundle類方法用於返回一個代表應用程式包物件。

iphone沙盒(sandbox)中的幾個目錄獲取方式:
  1. // 獲取沙盒主目錄路徑
  2. NSString *homeDir = NSHomeDirectory();
  3. // 獲取Documents目錄路徑
  4. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  5. NSString *docDir = [paths objectAtIndex:0];
  6. // 獲取Caches目錄路徑
  7. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  8. NSString *cachesDir = [paths objectAtIndex:0];
  9. // 獲取tmp目錄路徑
  10. NSString *tmpDir = NSTemporaryDirectory();
  1. // 獲取當前程式包中一個圖片資源(apple.png)路徑
  2. NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"apple" ofType:@"png"];
  3. UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];

例子:

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]];
}

相關文章