資料持久化的本質,就是把記憶體中的物件寫成檔案存到本地。iOS 的本地儲存空間稱為「沙盒(Sandbox)」,每個 App 各自獨立、互不干擾,這是系統層級的隔離保護機制。要談歸檔,得先搞清楚沙盒裡有哪些地方可以放東西。
要讓自訂類別的物件支援歸檔,必須遵循 NSCoding 協議,並實作 encodeWithCoder: 與 initWithCoder: 兩個方法。
#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
#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: 指定預期型別,可避免反序列化攻擊。