IOS中獲取各種文件的目錄路徑的方法

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]];
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章