在 Objective-C 中,將自訂類別物件儲存至檔案(持久化)需遵循 `NSCoding` 協定,實作序列化 (`encodeWithCoder:`) 與反序列化 (`initWithCoder:`),再透過 `NSKeyedArchiver`/`NSKeyedUnarchiver` 完成歸檔與解檔。
@interface Student : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *pwd;
@end
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.pwd forKey:@"pwd"];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.pwd = [aDecoder decodeObjectForKey:@"pwd"];
}
return self;
}
注意:這兩個方法只需在 `.m` 實作檔中寫入,`.h` 不需重複宣告。
NSArray *stuArr = @[student1, student2];
[NSKeyedArchiver archiveRootObject:stuArr toFile:@"/Users/Administrator/Desktop/4.plist"];
NSArray *loadedArr = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/Administrator/Desktop/4.plist"];
for (Student *s in loadedArr) {
NSLog(@"%@, %@", s.name, s.pwd);
}
遵循 `NSCoding` + `NSKeyedArchiver`/`Unarchiver` 是 Objective-C 物件持久化的標準路徑,適合輕量級資料儲存;大量資料建議改用 Core Data 或 SQLite。