1、沙盒機(jī)制介紹
iOS中的沙盒機(jī)制是一種安全體系。每個(gè)iOS程序都有一個(gè)獨(dú)立的文件系統(tǒng)(存儲(chǔ)空間),而且只能在對(duì)應(yīng)的文件系統(tǒng)中進(jìn)行操作,此區(qū)域被稱為沙盒。所有的非代碼文件都要保存在此,例如屬性文件plist、文本文件、圖像、圖標(biāo)、媒體資源等。
2、沙盒目錄結(jié)構(gòu)
/AppName.app 應(yīng)用程序的程序包目錄。由于應(yīng)用程序必須經(jīng)過(guò)簽名,所以不能在運(yùn)行時(shí)對(duì)這個(gè)目錄中的內(nèi)容進(jìn)行修改,否則會(huì)導(dǎo)致應(yīng)用程序無(wú)法啟動(dòng)。
/Documents/ 保存應(yīng)用程序的重要數(shù)據(jù)文件和用戶數(shù)據(jù)文件等。iTunes 同步時(shí)會(huì)備份該目錄。
/Library/Caches 保存應(yīng)用程序使用時(shí)產(chǎn)生的支持文件和緩存文件,還有日志文件最好也放在這個(gè)目錄。iTunes 同步時(shí)不會(huì)備份該目錄。
/Library/Preferences 保存應(yīng)用程序的偏好設(shè)置文件(使用 NSUserDefaults 類設(shè)置時(shí)創(chuàng)建,不應(yīng)該手動(dòng)創(chuàng)建)。
/tmp/ 保存應(yīng)用運(yùn)行時(shí)所需要的臨時(shí)數(shù)據(jù),iphone 重啟時(shí),會(huì)清除該目錄下所有文件。
3、獲取沙盒目錄
/*獲取程序的Home目錄*/
NSString *homeDirectory = NSHomeDirectory();
NSLog(@"path:%@",?homeDirectory);
/*獲取Document目錄*/
NSArray*documentArr =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
/*獲取Caches目錄*/
NSArray*cachesArr =NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
NSString*caches = [cachesArrobjectAtIndex:0];
NSLog(@"\npath-Caches%@", caches);
/* Library目錄*/
NSArray*libraryArr =NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
NSString*library = [libraryArrobjectAtIndex:0];
NSLog(@"\npath-Library%@", library);
/* tem目錄*/
NSString*tmpDir =NSTemporaryDirectory();
NSLog(@"%@", tmpDir);
NSString*document = [documentArrobjectAtIndex:0];
NSLog(@"\npath-Document:%@", document);
4、文件操作
/*寫(xiě)入文件*/
NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*docDir = [pathsobjectAtIndex:0];
if(!docDir) {
NSLog(@"Documents目錄未找到");
}
NSArray*array =@[@"姓名",@"性別"];
NSString*filePath = [docDirstringByAppendingPathComponent:@"arrayFile.txt"];
NSDictionary*dict =@{@"姓名":@"jcf",@"性別":@"男"};
NSString*dictPath = [docDirstringByAppendingPathComponent:@"dictFile.json"];
[arraywriteToFile:filePathatomically:YES];
[dictwriteToFile:dictPathatomically:YES];
/*讀取文件*/
NSArray*pathss =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*docDirs = [pathssobjectAtIndex:0];
NSString*arrayPaths = [docDirsstringByAppendingPathComponent:@"arrayFile.txt"];
NSArray*arrays = [[NSArrayalloc]initWithContentsOfFile:arrayPaths];
NSString*dictPaths = [docDirsstringByAppendingPathComponent:@"dictFile.json"];
NSDictionary*dicts = [NSDictionarydictionaryWithContentsOfFile:dictPaths];
NSLog(@"array:%@ *** dicts:%@", arrays,dicts);
/*創(chuàng)建文件*/ ? ? ?在Document下創(chuàng)建文件
NSArray*pathsss =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*documentsDirectory = [pathsssobjectAtIndex:0];
NSFileManager*fileManager = [NSFileManagerdefaultManager];
NSString*testDirectory = [documentsDirectorystringByAppendingPathComponent:@"test"];
//創(chuàng)建目錄
[fileManagercreateDirectoryAtPath:testDirectorywithIntermediateDirectories:YESattributes:nilerror:nil];
/*在test目錄寫(xiě)入文件*/
NSString*testPath = [testDirectorystringByAppendingPathComponent:@"mytest.txt"];
NSString*string =@"IOS開(kāi)發(fā)hello world";
[fileManagercreateFileAtPath:testPathcontents:[stringdataUsingEncoding:NSUTF8StringEncoding]attributes:nil];
NSString*testPath1 = [testDirectorystringByAppendingPathComponent:@"mytest1.json"];
NSDictionary*dict1 =@{@"姓名":@"jcf",@"性別":@"男"};
NSData*data1 = [NSJSONSerializationdataWithJSONObject:dict1options:NSJSONWritingPrettyPrintederror:nil];
[fileManagercreateFileAtPath:testPath1contents:data1attributes:nil];
*獲取test目錄所有文件名*/
//兩種方法獲?。簊ubpathsOfDirectoryAtPath和subpathsAtPath
NSArray*path =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*documents = [pathobjectAtIndex:0];
NSFileManager*fileManage = [NSFileManagerdefaultManager];
NSString*myDirectory = [documentsstringByAppendingPathComponent:@"test"];
/* subpathsOfDirectoryAtPath */
NSArray*file = [fileManagesubpathsOfDirectoryAtPath: myDirectoryerror:nil];
NSLog(@"%@",file);
/* subpathsAtPath */
NSArray*files = [fileManagesubpathsAtPath: myDirectory ];
NSLog(@"%@",files);
/*使用文件管理器:fileManager */
//創(chuàng)建文件管理器
NSFileManager*manager = [NSFileManagerdefaultManager];
NSArray*path_manager =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*documents_manager = [path_managerobjectAtIndex:0];
//指定待操作文件
[managerchangeCurrentDirectoryPath:documents_manager ];//將指定的擴(kuò)展名添加到現(xiàn)有路徑的最后一個(gè)組成部分上
NSString* fileTxt =@"testManager.txt";
NSArray*fileArray = [[NSArrayalloc]initWithObjects:@"one",@"two",@"three",nil];
NSData*data = [NSJSONSerializationdataWithJSONObject:fileArrayoptions:NSJSONWritingPrettyPrintederror:nil];
[fileManagercreateFileAtPath:fileTxtcontents:dataattributes:nil];
/*刪除文件*/
[managerremoveItemAtPath:fileTxterror:nil];
/*混合數(shù)據(jù)讀寫(xiě)操作*/
//用NSMutableData創(chuàng)建混合數(shù)據(jù),然后寫(xiě)到文件里。并按數(shù)據(jù)的類型把數(shù)據(jù)讀出來(lái)
NSString* fileName =@"testFileNSFileManager.txt";
NSArray*path_file =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*document_file = [path_fileobjectAtIndex:0];
//獲取文件路徑
NSString*pathStr = [document_filestringByAppendingPathComponent:fileName];
//待寫(xiě)入的數(shù)據(jù)
NSString*temp =@"nihao hello";
intdataInt =1234;
floatdataFloat =3.14f;
//創(chuàng)建數(shù)據(jù)緩沖
NSMutableData*writer = [[NSMutableDataalloc]init];
//將字符串添加到緩沖中
[writerappendData:[tempdataUsingEncoding:NSUTF8StringEncoding]];
//將其他數(shù)據(jù)添加到緩沖中
[writerappendBytes:&dataIntlength:sizeof(dataInt)];
[writerappendBytes:&dataFloatlength:sizeof(dataFloat)];
//將緩沖的數(shù)據(jù)寫(xiě)入到文件中
[writerwriteToFile:pathStratomically:YES];
//讀取數(shù)據(jù):
intintData;
floatfloatData =0.0;
NSString*stringData;
NSData*reader = [NSDatadataWithContentsOfFile:pathStr];
stringData = [[NSStringalloc]initWithData:[readersubdataWithRange:NSMakeRange(0, [templength])]
encoding:NSUTF8StringEncoding];
[reader getBytes:&intData range:NSMakeRange([temp length],sizeof(intData))];
[reader getBytes:&floatData range:NSMakeRange([temp length] +sizeof(intData),sizeof(floatData))];
NSLog(@"stringData:%@ intData:%d floatData:%f", stringData, intData, floatData);
附加:
1.在iOS8之前,我們獲取到沙盒中的document、cache、tmp之后,下一次模擬器或真機(jī)無(wú)論怎樣重啟,這具體的路徑是固定的了。(下面我們以Document為例介紹)
///Users/fanmingyang/Library/Developer/CoreSimulator/Devices/B9F35720-6386-445A-A0DA-0D911BFA64C3/data/Containers/Data/Application/176DA32A-E007-42F5-8716-3BBD80FFAB4F/Library/Documents
比如上面是iOS8之前獲取到的document路徑,在這之后,只要應(yīng)用不刪除,那么這個(gè)document路徑就一直是這個(gè)
2.在iOS8之后,蘋(píng)果可能考慮到安全因素,應(yīng)用每一次重啟,沙盒路徑都動(dòng)態(tài)的發(fā)生了變化。
iOS8中第一次啟動(dòng)時(shí)的路徑:
///Users/fanmingyang/Library/Developer/CoreSimulator/Devices/B9F35720-6386-445A-A0DA-0D911BFA64C3/data/Containers/Data/Application/D73211C2-497C-4C92-828C-584955C23BCB/Library/Documents
iOS8中第二次啟動(dòng)時(shí)的路徑:
///Users/fanmingyang/Library/Developer/CoreSimulator/Devices/B9F35720-6386-445A-A0DA-0D911BFA64C3/data/Containers/Data/Application/2B080462-8330-440E-AC26-
B9B15E065110/Library/Documents
3.可見(jiàn)。iOS8之后,每一次重啟路徑都發(fā)生了變化
4.雖然iOS8之后,沙盒的路徑發(fā)生了變化,但是并不代表你原來(lái)沙盒路徑中的數(shù)據(jù)發(fā)生了變化;同時(shí),也并不代表路徑會(huì)越來(lái)越多。
比如,我在document中寫(xiě)入了數(shù)據(jù)own.data后,下一次重啟后路徑變化了,那我們不禁要問(wèn),我們的own.data去哪兒呢?
其實(shí)這個(gè)不用擔(dān)心,蘋(píng)果已經(jīng)為你做好了.
1>蘋(píng)果會(huì)把你上一個(gè)路徑中的數(shù)據(jù)轉(zhuǎn)移到你新的路徑中。
2>你上一個(gè)路徑也會(huì)被蘋(píng)果毫無(wú)保留的刪除,只保留最新的路徑。