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

iOS 資料持久化:歸檔與反歸檔(NSCoding)完整實作

編輯:iOS 開發綜合

資料持久化的本質,就是把記憶體中的物件寫成檔案存到本地。iOS 的本地儲存空間稱為「沙盒(Sandbox)」,每個 App 各自獨立、互不干擾,這是系統層級的隔離保護機制。要談歸檔,得先搞清楚沙盒裡有哪些地方可以放東西。

沙盒目錄結構

  • Documents:存放需要長期保存的資料,例如使用者建立的文件。iTunes 備份會包含這個目錄。
  • Library/Caches:暫存檔案與快取。系統在空間不足時可能清除,因此不能放唯一副本。
  • Library/Preferences:偏好設定,例如「是否為首次啟動」這類旗標。
  • tmp:暫存檔案。與 Caches 的差別在於,這裡放的是「尚未處理完」的中間產物——例如未下載完成的影片,下載好之後就移到 Caches。
  • xxx.app:App 套件本身,包含編譯後的資源,唯讀不可修改。平時使用的 NSBundle 就是指這個目錄。

一、建立可被歸檔的 Person 類別

要讓自訂類別的物件支援歸檔,必須遵循 NSCoding 協議,並實作 encodeWithCoder: 與 initWithCoder: 兩個方法。

Person.h

#import <Foundation/Foundation.h>

// 若要對某類別的物件實作歸檔,必須讓該類別遵循 NSCoding 協議
@interface Person : NSObject <NSCoding>

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *gender;
@property (nonatomic, assign) NSInteger age;

- (id)initWithName:(NSString *)name gender:(NSString *)gender age:(NSInteger)age;

@end

Person.m

#import "Person.h"

@implementation Person

- (id)initWithName:(NSString *)name gender:(NSString *)gender age:(NSInteger)age {
    self = [super init];
    if (self) {
        // 1. 當屬性為 NSString、NSArray、NSDictionary、NSSet 時,語意特性宣告為 copy
        // 2. 定義完屬性後給實例變數賦值時,要使用 setter 方法
        // 3. 一定要注意屬性的記憶體管理
        self.name = name;
        self.gender = gender;
        self.age = age;
    }
    return self;
}

// 對物件歸檔時會呼叫此方法,為自己的實例變數進行歸檔
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeObject:_gender forKey:@"gender"];
    [aCoder encodeObject:@(_age) forKey:@"age"];
}

// 對物件反歸檔時會呼叫此方法,為實例變數進行反歸檔
- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.gender = [aDecoder decodeObjectForKey:@"gender"];
        self.age = [[aDecoder decodeObjectForKey:@"age"] integerValue];
    }
    return self;
}

- (void)dealloc {
    self.name = nil;
    self.gender = nil;
    [super dealloc];
}

@end

二、主程式中的歸檔與反歸檔

為了方便理解,這裡把 UI 元件的建立也一併寫出來。

#import "SecondViewController.h"
#import "Person.h"

@interface SecondViewController () <UITextFieldDelegate>
@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self customizeNavigationControl];

    self.view.backgroundColor = [UIColor whiteColor];

    // textField 1
    UITextField *firstFiled = [[UITextField alloc] initWithFrame:CGRectMake(30, 94, 260, 30)];
    firstFiled.delegate = self;
    firstFiled.tag = 100;
    firstFiled.placeholder = @"請輸入內容";
    firstFiled.autocorrectionType = UITextAutocorrectionTypeNo;
    firstFiled.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:firstFiled];
    [firstFiled release];

    // textField 2
    UITextField *secondFiled = [[UITextField alloc] initWithFrame:CGRectMake(30, 154, 260, 30)];
    secondFiled.delegate = self;
    secondFiled.tag = 101;
    secondFiled.autocorrectionType = UITextAutocorrectionTypeNo;
    secondFiled.placeholder = @"顯示上一個輸入框的內容";
    secondFiled.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:secondFiled];
    [secondFiled release];

    // 歸檔按鈕
    UIButton *pigeonholeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    pigeonholeButton.frame = CGRectMake(30, 214, 100, 30);
    [pigeonholeButton setTitle:@"歸檔" forState:UIControlStateNormal];
    [pigeonholeButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [pigeonholeButton addTarget:self action:@selector(pigeonholeClick:)
               forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pigeonholeButton];

    // 反歸檔按鈕
    UIButton *againstPigeonholeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    againstPigeonholeButton.frame = CGRectMake(190, 214, 100, 30);
    [againstPigeonholeButton setTitle:@"反歸檔" forState:UIControlStateNormal];
    [againstPigeonholeButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [againstPigeonholeButton addTarget:self action:@selector(againstPigeonholeClick:)
                     forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:againstPigeonholeButton];
}

#pragma mark - 歸檔

- (void)pigeonholeClick:(UIButton *)pigeonholeBtn {
    // 1. 取得輸入框內容
    UITextField *tf1 = (UITextField *)[self.view viewWithTag:100];
    UITextField *tf2 = (UITextField *)[self.view viewWithTag:101];

    // 封裝成 Person 物件
    Person *per = [[Person alloc] initWithName:tf1.text gender:tf2.text age:18];

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

    // 3. 執行歸檔
    [archiver encodeObject:per forKey:@"Tsummer"];

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

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

#pragma mark - 反歸檔

- (void)againstPigeonholeClick:(UIButton *)againstPigeonholeBtn {
    // 1. 依檔案路徑初始化 NSMutableData
    NSMutableData *mData = [NSMutableData dataWithContentsOfFile:[self getFilePath]];

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

    // 3. 執行反歸檔
    Person *per = [unarchiver decodeObjectForKey:@"Tsummer"];

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

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

    NSLog(@"反歸檔完成");
}

#pragma mark - 取得檔案路徑

- (NSString *)getFilePath {
    // 1. 先取得 Documents 目錄路徑
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                   NSUserDomainMask, YES) firstObject];

    // 2. 拼接檔案名稱
    NSString *newFilePath = [documentsPath stringByAppendingPathComponent:@"Tsummer.txt"];
    NSLog(@"%@", newFilePath);
    return newFilePath;
}

- (void)customizeNavigationControl {
    self.navigationItem.title = @"歸檔與反歸檔";
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

@end

幾個容易出錯的地方

key 必須成對一致:encode 與 decode 使用的 key 字串必須完全相同,任何一個字母不同就會拿到 nil,而且不會報錯,這種 bug 相當難查。

NSInteger 要装箱:encodeObject: 只接受物件,基本型別必須先轉成 NSNumber(如 @(_age)),取出來再轉回 integerValue。若改用 encodeInt:forKey: 搭配 decodeIntForKey: 也可以。

記得呼叫 finishEncoding / finishDecoding:漏掉的話資料可能不完整,或後續的編碼操作失效。

使用 NSSecureCoding 更安全:若歸檔的資料會從外部取得(例如網路下載後反序列化),建議遵循 NSSecureCoding 並實作 +supportsSecureCoding,同時改用 decodeObjectOfClass:forKey: 指定預期型別,可避免反序列化攻擊。

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