您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

搞懂 App 沙盒:Documents、Library 與 tmp 的分工與讀寫

編輯:iOS 開發綜合

每一個 iOS App 都被關在自己的沙盒裡,彼此無法互看。打開 App 的子目錄,通常會看到三個資料夾,各有各的用途:

三個目錄的職責

  • Documents:存放應用程式產生的資料。iTunes/iCloud 備份會包含這裡的內容,使用者也能在檔案 App 中看到。
  • Library:其中 Library/Preferences 存放以 NSUserDefaults 為基礎的偏好設定。
  • tmp:暫存檔案的家。同步時 iTunes 不會備份這裡,因此當檔案不再需要時,App 有責任自行刪除,否則會白白佔用使用者裝置的空間。

取得路徑

// Documents 目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *docFile = [documentsDirectory stringByAppendingPathComponent:@"theFile.txt"];

// tmp 目錄
NSString *tempPath = NSTemporaryDirectory();
NSString *tempFile = [tempPath stringByAppendingPathComponent:@"theFile.txt"];

兩段程式都會得到 theFile.txt 的完整路徑,差別只在於備份策略與生命週期。

把陣列寫入檔案

NSArray/NSDictionary 提供了 writeToFile:atomically:,存檔不必自己 fopen:

NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:string1];
[array addObject:string2];
[array addObject:string3];
[array addObject:string4];
[array writeToFile:[self filePath] atomically:YES];
[array release];

atomically:YES 會先寫入暫存檔再取代目標檔,過程中斷電或跳出 App 也不會留下半個檔案,預設就該開著。

從檔案讀回陣列

NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
string1 = [array objectAtIndex:0];
string2 = [array objectAtIndex:1];
string3 = [array objectAtIndex:2];
string4 = [array objectAtIndex:3];
[array release];

這種「直接存檔/讀檔」的序列化只適用於 plist 型別(數字、字串、日期、資料、陣列、字典)。若檔案不存在,initWithContentsOfFile: 會回傳 nil,取元素前務必先判斷,或改用 NSFileManager 檢查檔案是否存在並寫入預設值。

資料量再大一點、需要查詢與局部更新時,就該換成 Core Data 或 SQLite 了。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved