iOS 的持久化手段有好幾種:plist、SQLite、Core Data、NSUserDefaults,以及本文要談的物件歸檔(Object Archiving)。當你想把一整個自訂物件(連同它的屬性)原樣存到檔案、之後再原樣讀回來時,NSKeyedArchiver 是最直覺的選擇。
要被歸檔的類別必須遵循 NSCoding 協定,並實作兩個方法:encodeWithCoder: 負責「寫出去」,initWithCoder: 負責「讀回來」。
//
// Student.h
//
#import <Foundation/Foundation.h>
// 若要支援物件歸檔,必須實作 NSCoding 協定
@interface Student : NSObject <NSCoding>
{
NSString *studentId;
NSString *studentName;
NSString *studentClass;
}
@property (nonatomic, retain) NSString *studentId;
@property (nonatomic, retain) NSString *studentName;
@property (nonatomic, retain) NSString *studentClass;
@end
//
// Student.m
//
#import "Student.h"
@implementation Student
@synthesize studentId, studentName, studentClass;
// 歸檔時的編碼
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:studentId forKey:@"studentId"];
[aCoder encodeObject:studentName forKey:@"studentName"];
[aCoder encodeObject:studentClass forKey:@"studentClass"];
}
// 讀檔時的解碼,完成物件實例化
-(id)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self) {
self.studentId = [aDecoder decodeObjectForKey:@"studentId"];
self.studentName = [aDecoder decodeObjectForKey:@"studentName"];
self.studentClass = [aDecoder decodeObjectForKey:@"studentClass"];
}
return self;
}
@end
小提醒:每個屬性都要有一組成對的 key,且編碼與解碼必須完全一致,否則還原時會拿到 nil。另外,initWithCoder: 中別忘了先呼叫 [super init],這在原始寫法中常被省略。
//
// ios24_saveObjectToFileViewController.m
//
#import "ios24_saveObjectToFileViewController.h"
#import "Student.h"
@implementation ios24_saveObjectToFileViewController
@synthesize tfId, tfName, tfClass;
#pragma mark - 存檔
-(IBAction)save{
NSString *savePath = [self getFilePath];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archer = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
Student *stu = [[Student alloc] init];
stu.studentId = tfId.text;
stu.studentName = tfName.text;
stu.studentClass = tfClass.text;
[archer encodeObject:stu forKey:@"stuobj"];
[archer finishEncoding];
[data writeToFile:savePath atomically:YES];
NSLog(@"保存成功");
}
#pragma mark - 讀檔
-(IBAction)read{
NSString *readPath = [self getFilePath];
NSData *data = [[NSData alloc] initWithContentsOfFile:readPath];
if (data.length > 0) {
NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
Student *stu = [unArchiver decodeObjectForKey:@"stuobj"];
[unArchiver finishDecoding];
tfId.text = stu.studentId;
tfName.text = stu.studentName;
tfClass.text = stu.studentClass;
}
}
#pragma mark - 檔案路徑
-(NSString *)getFilePath{
// 取得 Documents 目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths lastObject];
// 拼接完整路徑
return [documentPath stringByAppendingPathComponent:@"student.achiver"];
}
#pragma mark - 鍵盤與生命週期
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
tfId.delegate = self;
tfName.delegate = self;
tfClass.delegate = self;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
@end
NSKeyedArchiver 包裝 → encodeObject:forKey: 編碼 → finishEncoding 收尾 → writeToFile:atomically: 落盤。initWithContentsOfFile: 讀回二進位串流 → NSKeyedUnarchiver 包裝 → decodeObjectForKey: 還原物件 → finishDecoding 收尾 → 回填介面。NSSearchPathForDirectoriesInDomains 取得 Documents 目錄後拼接檔名,避免寫死路徑。相較於自己拆解屬性組 plist,歸檔的優勢是「類別結構改了,只要同步調整 encode/decode 即可」,且能保存物件圖(含巢狀物件與多向參照)。要注意的是 NSKeyedArchiver 已不建議用於大量資料或不相容版本之間的傳遞,這類情境應改用 Core Data 或 Codable。