Archiver 是 iOS 中常見的資料持久化方式,與 Plist 不同,它可以保存自訂物件。自訂類別要能被歸檔,必須實作 NSCoding 協議。
- (id)initWithCoder:(NSCoder *)aDecoder;
- (void)encodeWithCoder:(NSCoder *)aCoder;- (NSString *)filePath {
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSAllDomainsMask, YES);
NSString *dirPath = dirPaths[0];
return [dirPath stringByAppendingPathComponent:@"aa.archiver"];
}NSNumber、NSArray、NSDictionary、NSString、NSData 等物件已實作 NSCoding,可直接用 NSKeyedArchiver 保存。
NSArray *arr = @[@"ttt", @"BBB", @25];
[NSKeyedArchiver archiveRootObject:arr toFile:filePath];
NSArray *arr1 = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInt:self.age forKey:@"age"];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
[self setName:[aDecoder decodeObjectForKey:@"name"]];
[self setAge:[aDecoder decodeIntForKey:@"age"]];
}
return self;
}若子類別也需要歸檔,記得先呼叫父類別的 encodeWithCoder 與 initWithCoder,再處理自己的屬性。