首先我們來認識一下沙盒,沙盒就是每一個app對應的一塊存儲空間。
沙盒中有下列檔案夾
Documents:文檔 最常打交道的目錄 iTunes會備份和恢複此檔案夾的内容
Library/Caches : 緩存檔案夾 用來儲存緩存資料 不會備份和恢複
Library/Preferences:使用者偏好設定 iTunes會備份和恢複此檔案夾的内容
tmp:臨時檔案夾 存放臨時檔案 不會備份和恢複 此檔案夾内容會不定時清除
下面我們通過代碼來看一下沙盒的使用
NSString *homePath = NSHomeDirectory();
NSLog(@"沙箱根目錄:%@",homePath);
//擷取Documents路徑兩種方法
NSString *documentsPath1 = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *documentsPath2 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
NSLog(@"%@ %@",documentsPath1,documentsPath2);
//擷取緩存檔案夾路徑
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
//擷取臨時檔案夾路徑
NSString *tmpPath = NSTemporaryDirectory();
NSLog(@"緩存:%@ 臨時:%@",cachePath,tmpPath);
//往document中寫.txt
NSString *text = @"過年好!";
NSString *path = [documentsPath1 stringByAppendingPathComponent:@"abc.txt"];
[text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
//往document中寫.plist plist中存放數組
NSString *filePath = [documentsPath1 stringByAppendingPathComponent:@"names.plist"];
NSArray *names = @[@"a",@"b",@"c"];
[names writeToFile:filePath atomically:YES];
輸出結果如下:
下面我們複制documents的位址,通過finder前往目前目錄,看一下plist檔案,還有txt檔案是否寫入。結果如圖:
對于plist檔案讀寫,還有不了解的朋友請參考這篇微網誌:
http://blog.csdn.net/lee727n/article/details/70303766