前幾天有人問起iOS沙盒路徑如何獲取,時間太久沒記起來,幾天有空,回顧一下:
沙盒 : 其實對於每一個應用程序都有唯一的一個本地文件與之對應 名字由系統隨機生成這個文件就是沙盒
沙盒機制 :沙河機制 其實就是對每一個應用程序 的資源起到一個保護作用當前 程序不允許訪問其他程序的資源 其他程序也不允許 訪問當前程序的的資源
對於每一個應用程序的沙盒文件都包含以下文件
1.documents 用來存儲持久化數據文件 .如果我們想對一個文件進行長久存儲就放在該文件夾下
2.Libary
(a)Caches : 緩存文件,存放已經下載完成的視頻音頻 圖片等一般我們會在該文件下 創建Images Audioes Videoes等文件 分別存放圖片視頻音頻
(b)Perfrences : 用於存放用戶的偏好設置比如 用於判斷程序是否是第一次啓動的plist文件就放在該文件夾下的
3.temp : 存放未下載完成的視頻音頻等 一般我們會將下載完成的視頻音頻在手動移動到Caches中
XXX.app :應用程序包 ,應用程序資源都來源於包,而包也是我們上傳到appStore 以及用戶從AppStore下載的文件對於包內的資源我們不能進行修改 更不能刪除
另外,對於以上文件都是由系統創建 不允許隨意更改我們只能刪改自己創建的文件;
代碼如下
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
NSString *applicationPath = [[NSBundle mainBundle] resourcePath];
進而瞭解一下文件的簡單存儲:
寫入一段字符串:helloWorld!
NSString *str1 = @"helloWorld";
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"test.TXT"];
[str1 writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
保存數組做plist文件
NSString *str2 = str1;
//創建一個數組
NSArray *arr = @[str1,str2];
//拼接文件路徑
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"arr.plist"];
//寫入
[arr writeToFile:filePath atomically:YES];
保存字典爲xml
NSDictionary *dic = @{@"t1":str1 ,@"t2":str2};
//文件拼接
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"dic.xml"];
[dic writeToFile:filePath atomically:YES];
保存data
NSData *data = [str1 dataUsingEncoding:NSUTF8StringEncoding];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"data.data"];
[data writeToFile:filePath atomically:YES];
本地文件讀取(txt文件爲例)
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"f1" ofType:@".txt"];
NSString *str = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];