某個iphone工程進行文件操作有此工程對應的指定的位置,不能逾越。
iphone沙箱模型的有四個文件夾,分別是什么,永久數據存儲一般放在什么位置,得到模擬器的路徑的簡單方式是什么.
documents,tmp,app,Library。
(NSHomeDirectory()),
手動保存的文件在documents文件里
Nsuserdefaults保存的文件在tmp文件夾里
Documents 目錄:您應該將所有de應用程序數據文件寫入到這個目錄下。這個目錄用于存儲用戶數據或其它應該定期備份的信息。
AppName.app 目錄:這是應用程序的程序包目錄,包含應用程序的本身。由于應用程序必須經過簽名,
所以您在運行時不能對這個目錄中的內容進行修改,否則可能會使應用程序無法啟動。
Library 目錄:這個目錄下有兩個子目錄:Caches 和 Preferences
Preferences 目錄包含應用程序的偏好設置文件。您不應該直接創建偏好設置文件,而是應該使用NSUserDefaults類來取得和設置應用程序的偏好.
Caches 目錄用于存放應用程序專用的支持文件,保存應用程序再次啟動過程中需要的信息。
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類方法用于返回一個代表應用程序包的對象。
文件IO寫入
1,將數據寫到Documents目錄:
- (BOOL)writeApplicationData:(NSData *)data toFile:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
if (!docDir) {
NSLog(@”Documents directory not found!”); return NO;
}
NSString *filePath = [docDir stringByAppendingPathComponent:fileName];
return [data writeToFile:filePath atomically:YES];
}
2,從Documents目錄讀取數據:
- (NSData *)applicationDataFromFile:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:fileName];
NSData *data = [[[NSData alloc] initWithContentsOfFile:filePath] autorelease];
return data;
}
NSSearchPathForDirectoriesInDomains這個主要就是返回一個絕對路徑用來存放我們需要儲存的文件。
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"shoppingCar.plist"];
}
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]];
}
iphone常見私有API的應用(比如直接發送短信,訪問沙箱之外的磁盤文件)