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

iOS 檔案讀寫與歸檔解檔:持久化儲存的兩條路徑

編輯:iOS 開發綜合

資料持久化的本質,是把記憶體中的資料寫成檔案存到本地。iOS 的實現方式是「沙盒機制」——系統為每個 App 建立獨立目錄(名稱隨機),App 之間無法互相存取對方沙盒內的內容,以此達到隔離與保護。

沙盒四個主要位置

  1. Documents:存放需要長期保存的資料。iTunes/iCloud 備份會包含此目錄。
  2. xxx.app:App 套件,包含載入所需的所有資源,唯讀不可修改。平時使用的 NSBundle 就是指這個目錄。
  3. Library:
    • Caches:本地快取,存放想暫時保留的資料,如下載的影片、音樂、圖片。系統空間不足時可能清除。
    • Preferences:存放使用者偏好設定,例如「程式是否為第一次啟動」。
  4. tmp:存放尚未下載完成的影片、音訊等暫存檔;下載完成後再移到 Caches。

本文分兩部分:先用「檔案直接讀寫」處理 NSString/NSArray/NSDictionary,再用「歸檔」處理自訂物件。

一、檔案直接讀寫

先建立兩個輸入框與三顆按鈕:

#import "WYLReadAndWriteViewController.h"
#import "WYLArchive.h"

@interface WYLReadAndWriteViewController () <UITextFieldDelegate>
@end

@implementation WYLReadAndWriteViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"文件讀寫";

    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(40, 84, 220, 40)];
    textField.tag = 100;
    textField.placeholder = @"請輸入內容";
    textField.delegate = self;
    textField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:textField];
    [textField release];

    UITextField *textField2 = [[UITextField alloc] initWithFrame:CGRectMake(40, 174, 220, 40)];
    textField2.tag = 101;
    textField2.placeholder = @"顯示上一個輸入框的內容";
    textField2.delegate = self;
    textField2.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:textField2];
    [textField2 release];

    UIButton *writeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    writeButton.frame = CGRectMake(45, 260, 60, 30);
    [writeButton setTitle:@"寫入" forState:UIControlStateNormal];
    [writeButton addTarget:self action:@selector(write:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:writeButton];

    UIButton *readButton = [UIButton buttonWithType:UIButtonTypeSystem];
    readButton.frame = CGRectMake(190, 260, 60, 30);
    [readButton setTitle:@"讀取" forState:UIControlStateNormal];
    [readButton addTarget:self action:@selector(read:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:readButton];

    UIButton *push = [UIButton buttonWithType:UIButtonTypeSystem];
    push.frame = CGRectMake(120, 310, 60, 30);
    [push setTitle:@"歸檔範例" forState:UIControlStateNormal];
    [push addTarget:self action:@selector(push:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:push];
}

取得檔案路徑

NSSearchPathForDirectoriesInDomains 的三個參數分別是:要查的目錄、搜尋範圍(自己的檔案都在 User Domain)、是否回傳絕對路徑。因為這個 API 源自 Mac OS(一台電腦可能有多個使用者),所以回傳值是陣列;在 iOS 上只有一個使用者,因此取 firstObject 即可。

- (NSString *)getFilePath {
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                              NSUserDomainMask, YES) firstObject];
    NSString *newPath = [filePath stringByAppendingPathComponent:@"test.txt"];
    NSLog(@"%@", newPath);
    return newPath;
}

寫入

檔案直接讀寫只支援 NSString、NSArray、NSDictionary、NSData 及其子類。寫入用 writeToFile:atomically:,讀取則用各類別自帶的 ...WithContentsOfFile: 方法。

要特別注意:容器類別(陣列、字典)裡的元素,也必須是這幾種可讀寫的型別之一,放入自訂物件會直接寫入失敗。

- (void)write:(UIButton *)button {
    UITextField *tf = (UITextField *)[self.view viewWithTag:100];
    NSString *content = tf.text;

    UITextField *tf2 = (UITextField *)[self.view viewWithTag:101];
    NSString *content1 = tf2.text;

    NSString *newFilePath = [self getFilePath];

    // 寫入字串
    // BOOL isSucceed = [content writeToFile:newFilePath
    //                            atomically:YES
    //                              encoding:NSUTF8StringEncoding
    //                                 error:&error];

    // 寫入陣列
    // NSArray *arr = @[content, content1];
    // BOOL isSucceed = [arr writeToFile:newFilePath atomically:YES];

    // 寫入字典
    NSDictionary *dic = @{@"tf1": content, @"tf2": content1};
    BOOL isSucceed = [dic writeToFile:newFilePath atomically:YES];
    NSLog(@"寫入結果:%d", isSucceed);
}

讀取

每次寫入都會覆蓋整個檔案。若要保留既有內容,必須先讀出來,與新資料合併後再一次寫入。

- (void)read:(UIButton *)button {
    NSString *filePath = [self getFilePath];

    // 讀取字串
    // NSString *content = [NSString stringWithContentsOfFile:filePath
    //                                                 encoding:NSUTF8StringEncoding
    //                                                    error:nil];

    // 讀取陣列
    // NSArray *arr = [NSArray arrayWithContentsOfFile:filePath];

    // 讀取字典
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filePath];

    UITextField *tf = (UITextField *)[self.view viewWithTag:100];
    UITextField *tf1 = (UITextField *)[self.view viewWithTag:101];
    tf.text = dic[@"tf2"];
    tf1.text = dic[@"tf1"];
}

二、歸檔與解檔

自訂物件無法用上面的方法直接存,必須走 NSCoding 這條路:讓類別遵循 NSCoding 協議,再由 NSKeyedArchiver 序列化。

Person 類別的實作(encodeWithCoder: 與 initWithCoder:)與一般 NSCoding 範例相同,此處省略,重點在於呼叫端的流程。

歸檔

- (void)file:(UIButton *)button {
    UITextField *tf1 = (UITextField *)[self.view viewWithTag:100];
    UITextField *tf2 = (UITextField *)[self.view viewWithTag:101];

    Person *person = [[Person alloc] initWithName:tf1.text gender:tf2.text age:18];

    // 1. 建立歸檔物件
    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    // 2. 執行歸檔
    [archiver encodeObject:person forKey:@"archiver"];
    [person release];

    // 3. 結束歸檔;結束之後再歸檔無效
    [archiver finishEncoding];
    [archiver release];

    // 4. 將 data 寫入檔案
    [data writeToFile:[self getPath] atomically:YES];
}

解檔

- (void)archive:(UIButton *)button {
    // 1. 依檔案初始化 NSMutableData
    NSMutableData *data = [NSMutableData dataWithContentsOfFile:[self getPath]];

    // 2. 建立反歸檔物件
    NSKeyedUnarchiver *unarchive = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

    // 3. 執行解檔
    Person *person = [unarchive decodeObjectForKey:@"archiver"];

    // 4. 結束反歸檔
    [unarchive finishDecoding];
    [unarchive release];

    UITextField *tf1 = (UITextField *)[self.view viewWithTag:100];
    UITextField *tf2 = (UITextField *)[self.view viewWithTag:101];
    tf1.text = person.gender;
    tf2.text = person.name;
}

兩種方式該怎麼選

檔案直接讀寫適合結構簡單、資料量小的情境,例如幾個設定值或一小份清單。程式碼短、無需額外定義類別,缺點是每次都要整檔重寫,且只能處理那四種基礎型別。

歸檔(NSCoding)適合複雜的物件圖:只要每個類別都遵循 NSCoding,就能把一整棵物件樹序列化,包括巢狀的自訂物件與集合類別。代價是編碼/解碼的效能不如前者的 plist 方式,大量資料時差距明顯。

若是 Core Data 或大量結構化資料,兩者都不合用,應該直接考慮 SQLite(或 FMDB 封裝)與 Core Data;若是少量的 key-value 設定,NSUserDefaults 會比手動寫檔更合適。

最後提醒:範例中的 release 屬於 MRC 語法。專案若已啟用 ARC,請全部移除這些呼叫,否則會編譯失敗。

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