在 iOS 中,若要把普通的陣列存成檔案,可以直接呼叫 writeToFile:atomically: 寫入,再用 initWithContentsOfFile: 讀回。然而,當陣列裡存的是自訂物件時,就不能用這種簡便方法了,必須透過「物件歸檔(NSCoding)」來實現。以下說明完整流程。
讓自訂類別採用 NSCoding 協議,並實作 encodeWithCoder:(負責編碼存檔)與 initWithCoder:(負責解碼還原)兩個方法:
@interface CourseModel : CYZBaseModel <NSCoding>
@end
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
self.courseName = [aDecoder decodeObjectForKey:@"courseName"];
self.courseTeacher = [aDecoder decodeObjectForKey:@"courseTeacher"];
self.courseTime = [aDecoder decodeObjectForKey:@"courseTime"];
self.courseLocation = [aDecoder decodeObjectForKey:@"courseLocation"];
self.shouldUseTip = [aDecoder decodeBoolForKey:@"shouldUseTip"];
self.row = [aDecoder decodeIntegerForKey:@"row"];
self.section = [aDecoder decodeIntegerForKey:@"section"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.courseName forKey:@"courseName"];
[aCoder encodeObject:self.courseTeacher forKey:@"courseTeacher"];
[aCoder encodeObject:self.courseTime forKey:@"courseTime"];
[aCoder encodeObject:self.courseLocation forKey:@"courseLocation"];
[aCoder encodeBool:self.shouldUseTip forKey:@"shouldUseTip"];
[aCoder encodeInteger:self.row forKey:@"row"];
[aCoder encodeInteger:self.section forKey:@"section"];
}
關鍵在於:每一個需要保存的屬性,都要在 encode 時編碼、在 init 時解碼,且 key 必須一一對應。
把檔案存到沙盒的 Documents 目錄下:
- (NSString *)filePath {
return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"course.plist"];
}
呼叫 NSKeyedArchiver 的 archiveRootObject:toFile: 即可把物件(或其陣列)寫入檔案:
NSString *path = [self filePath]; [NSKeyedArchiver archiveRootObject:self.allCourses toFile:path];
呼叫 NSKeyedUnarchiver 的 unarchiveObjectWithFile: 還原物件;若讀取失敗(檔案不存在)則給一個空的初始值:
NSString *path = [self filePath];
self.allCourses = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
if (self.allCourses == nil) {
self.allCourses = [NSMutableArray array];
}
透過這套歸檔與反歸檔機制,就能把自訂物件的陣列或字典完整地持久化到本機,下次啟動 App 時再還原,是很常見的本地資料保存做法。