iOS開發——儲存自訂對象數組、字典到檔案
在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"];}
三、調用NSKeyedArchived類的類方法:- (void)archiveRootObject:toFile:寫入檔案
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]; }