iOS沙盒以及基於文件的持久化

 

新建一個demo項目緩存

在 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中調用以下代碼app

 

NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentDirectory = [documentDirectories firstObject];
    NSLog(@"documentDirectory = %@",documentDirectory);

輸出的路徑,在finder中能夠前往文件夾打開spa

能夠看到以下的目錄結構.net

 


Documents 目錄是保存數據,備份或者同步也是這個目錄
Library/Caches app產生的數據會保存在這裏,用來記住每次運行的數據,可是不會被同步code

Library/Preferences NSUserDefault類操做的數據blog

temp/ 不會備份,可是不須要的時候仍是能清處理,NSTemporaryDirectory圖片

由於應用是在沙箱(sandbox)中的,在文件讀寫權限上受到限制,只能在幾個目錄下讀寫文件:資源

  • Documents:應用中用戶數據能夠放在這裏,iTunes備份和恢復的時候會包括此目錄
  • tmp:存放臨時文件,iTunes不會備份和恢復此目錄,此目錄下文件可能會在應用退出後刪除
  • Library/Caches:存放緩存文件,iTunes不會備份此目錄,此目錄下文件不會在應用退出刪除

constructing a file path開發


   獲取沙盒路徑

- (NSString *)itemArchivePath{
    NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSString *documentDirectory =  [documentDirectories firstObject];
    
    return [documentDirectory stringByAppendingPathComponent:@"items.archive"];

}


    

- (BOOL)saveChanges{
    NSString *path = [self itemArchivePath];
    return [NSKeyedArchiver archiveRootObject:self.privateItems toFile:path];
    
}

保存的結果是文件系統中會多出一個items.archive的文件rem


 
[[NSFileManager defaultManager] removeItemAtPath:imagePath error:nil];

 

 

 

 

保存圖片到沙盒路徑

 

讀取沙盒路徑下的文件

 

獲取Bundle中的資源文件

NSString *myFilePath = [[NSBundle mainBundle]
                            pathForResource:@"f"
                            ofType:@"txt"];
    NSString *myFileContent=[NSString stringWithContentsOfFile:myFilePath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"bundel file path: %@ \nfile content:%@",myFilePath,myFileContent);

 

 

操做沙盒中的文件以及文件夾

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 *data2 = [NSData dataWithContentsOfFile:[self dataFilePath]];
    }

 

 

 

參考資料

http://blog.csdn.net/xingxing513234072/article/details/24184917

 

複習問題

1. 如何獲取沙盒中的document路徑?

2,開發者能夠直接進行讀寫操做的路徑有哪些?緩存型的數據能夠放在哪裏?須要持久化保存的數據應該放在哪裏?

3,在沙盒中document路徑下創建一個ScreenShotImages的文件夾,並往其中保存屏幕截圖的內容。

4,讀取沙盒中document路徑下的全部文件或者文件夾,並打印文件或者文件夾的名稱

5,請寫出刪除指定目錄document文件夾下log.txt 的代碼

6,刪除document文件夾下ScreenShotImages文件夾的代碼

相關文章
相關標籤/搜索