2014-11-25 22:26html
在ios中,要保存普通的数组到文件能够直接调用-wirteToFile:atomically:方法写入,而且能够经过NSArray的方法-initWithContentOfFile:来读文件初始化数组。然而,当要保存的数组中存储的数据对象是自定义对象时,就得经过对象归档的方法来实现了,具体来讲ios
1、自定义对象实现归档协议,并实现方法- (id)initWithCoder:和方法- (void)encodeWithCoder:数组
@interface CourseModel : CYZBaseModel <NSCoding>
- (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"]; }
2、得到保存文件的路径atom
- (NSString *)filePath { return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"course.plist"]; }
3、调用NSKeyedArchived类的类方法:- (void)archiveRootObject:toFile:写入文件 spa
NSString *path = [self filePath]; [NSKeyedArchiver archiveRootObject:self.allCourses toFile:path];
4、调用NSKeyedUnarchiver类的类方法:- (id)unarchiveObjectWithFile:读文件.net
NSString *path = [self filePath]; self.allCourses = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; if (self.allCourses == nil) { self.allCourses = [NSMutableArray array]; }