IOS development-save custom object arrays and dictionaries to files
In ios, to save an ordinary array to a file, you can directly call-wirteToFile: atomically: Method to write data, and you can use the NSArray method-initWithContentOfFile: to read the file and initialize the array. However, when the data objects stored in the array to be saved are custom objects, you must use the object archiving method. Specifically
I. Implement the archive protocol for custom objects and implement the method-(id) initWithCoder: And method-(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"];}
2. Obtain the path for saving the file
- (NSString *)filePath{ return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"course.plist"];}
3. Call the NSKeyedArchived class method:-(void) archiveRootObject: toFile: Write File
NSString *path = [self filePath]; [NSKeyedArchiver archiveRootObject:self.allCourses toFile:path];
4. Call the class method of the NSKeyedUnarchiver class:-(id) unarchiveObjectWithFile: Read the file
NSString *path = [self filePath]; self.allCourses = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; if (self.allCourses == nil) { self.allCourses = [NSMutableArray array]; }