In iOS, to save a normal array to a file you can directly call-wirtetofile:atomically: Method Write, and you can-initwithcontentoffile by Nsarray method: to read the file initialization array. However, when the data object stored in the array to be saved is a custom object, it has to be done by means of an object archive, specifically
The custom object implements the archiving protocol, and implements the method-(ID) Initwithcoder: And Method-(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"];}
Second, get the path to save the file
-(NSString *) filepath{ return [[Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES ) objectatindex:0] stringbyappendingpathcomponent:@ "course.plist"];}
third, call the class method of the Nskeyedarchived class:-(void) Archiverootobject:tofile: Write File
NSString *path = [self filePath]; [Nskeyedarchiver archiveRootObject:self.allCourses Tofile:path];
Iv. calling the class method of the Nskeyedunarchiver class:-(ID) unarchiveobjectwithfile: Read file
NSString *path = [self filePath]; self.allcourses = [Nskeyedunarchiver Unarchiveobjectwithfile:path]; if (self.allcourses = = nil) { self.allcourses = [Nsmutablearray array]; }
iOS development-Save custom object arrays, dictionaries to files