在ios中,要保存普通的數組到文件可以直接調用-wirteToFile:atomically:方法寫入,並且可以通過NSArray的方法-initWithContentOfFile:來讀文件初始化數組。然而,當要保存的數組中存儲的數據對象是自定義對象時,就得通過對象歸檔的方法來實現了,具體來說
一、自定義對象實現歸檔協議,並實現方法- (id)initWithCoder:和方法- (void)encodeWithCoder:
@interface CourseModel : CYZBaseModel
- (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"];
}
二、獲得保存文件的路徑
- (NSString *)filePath
{
return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"course.plist"];
} NSString *path = [self filePath];
[NSKeyedArchiver archiveRootObject:self.allCourses toFile:path];
四、調用NSKeyedUnarchiver類的類方法:- (id)unarchiveObjectWithFile:讀文件
NSString *path = [self filePath];
self.allCourses = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
if (self.allCourses == nil) {
self.allCourses = [NSMutableArray array];
}