iOS沙箱機制
第一、什麼是沙箱
IOS應用程式只能在為該改程式建立的檔案系統中讀取檔案,不可以去其它地方訪問,此地區被成為沙箱
第二、儲存內容
所有的非代碼檔案都要儲存在此,例像,表徵圖,聲音,映像,屬性列表,文字檔等
第三、作用
iOS沙箱為程式運行提供了很好的安全保障
第四、目錄
1、Documents目錄:這個目錄用於儲存使用者資料或其它應該定期備份的資訊,蘋果建議將程式中建立的或在程式中瀏覽到的檔案資料儲存在該目錄下,iTunes備份和恢複的時候會包括此目錄。
2、AppName.app 目錄:這是應用程式的程式包目錄,包含應用程式的本身。由於應用程式必須經過簽名,所以您在運行時不能對這個目錄中的內容進行修改,否則可能會使應用程式無法啟動。
3、Library目錄:這個目錄下有兩個子目錄:Caches 和 Preferences
Preferences 目錄包含應用程式的喜好設定檔案。您不應該直接建立喜好設定檔案,而是應該使用NSUserDefaults類來取得和設定應用程式的偏好
Caches 目錄用於存放應用程式專用的支援檔案,儲存應用程式再次啟動過程中需要的資訊。
4、tmp 目錄:這個目錄用於存放臨時檔案,儲存應用程式再次啟動過程中不需要的資訊,重啟後清空
itues和iphone同步時,備份所有的Document和library檔案
第五、擷取不同目錄的方法
1、擷取document目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
2、擷取cache目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString* cachesDirectory = [paths objectAtIndex:0];
3、擷取tmp目錄路徑的方法:
NSString *tmpDir = NSTemporaryDirectory();
4、擷取應用程式程式包中資源檔路徑的方法:
//例如擷取程式包中一個圖片資源(apple.png)路徑的方法:
NSString *imagePath = [[NSBundlemainBundle]pathForResource:@"apple"ofType:@"png"];
第六、檔案I/O操作
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;
}