Local persistence of simple objects (Nsstring,nsdata,nsdictionary,nsarray and their subclasses), written to the file by WriteToFile
For local persistence of complex objects (other than simple objects, such as custom person classes), the complex object is first converted to NSData (which is called an archive) and then writetofile written to the file;
First, simple object local persistence steps:
Nsdictionary,nsarray type data operation steps are similar;
NSData type data steps are as follows:
Complex object local Persistence steps:
#pragma mark-localization-------Custom person class for complex objects
//1. Locate the Documents folder directory
nsstring *documentpath = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, NSUserDomainMask, YES) OBJECTATINDEX:0];
//2. Creating a Person object
Person *per= [[Person alloc] init];
per.name = @ "Hhhboy";
#pragma Mark Archive
//3.1 creates a nsmutabledata that initializes the archive tool's
nsmutabledata *data = [Nsmutabledata data];
//3.2 Creating an archive tool
nskeyedarchiver *archiver = [[Nskeyedarchiver alloc] initforwritingwithmutabledata:data];
//3.3 Archive The Person object to be archived
[archiver encodeobject:per forkey:@ "person"];
//3.4 End Archive
[Archiver finishencoding];
//4. Storing archived content nsmutabledata on-premises
nsstring *personpath = [documentpath stringbyappendingpathcomponent:@ "Person.plist"];
[Data Writetofile:personpath atomically:yes];
NSLog (@ "%@", Personpath);
#pragma mark-de-document
//1. Find the data that will be solved
NSData *resultdata = [NSData Datawithcontentsoffile:personpath];
//nslog (@ "resultdata =%@", resultdata);
//2. Creating a Profile tool
nskeyedunarchiver *unarchiver = [[Nskeyedunarchiver alloc] initforreadingwithdata:resultdata];
//3. Solving a Person object [to use object receive]
Person *newper = [unarchiver decodeobjectforkey:@ ' person '];
//4. Closing the solution file
[Unarchiver finishdecoding];
where the. m file in the custom class is:
@implementation Person
//Archive all attributes
-(void) Encodewithcoder: (Nscoder *) Acoder {
[Acoder encodeObject:self.name forkey:@ "name"];
[Acoder encodeObject:self.gender forkey:@ "gender"];
[Acoder encodeInteger:self.age forkey:@ "age"];
}
//Solve files (reverse archive)
-(Instancetype) Initwithcoder: (Nscoder *) Adecoder {
Self = [super init];
if (self) {
self.name = [adecoder decodeobjectforkey:@ "name"];
Self.gender = [Adecoder decodeobjectforkey:@ "Gender"];
self.age = [Adecoder decodeintegerforkey:@ "age"];
}
return self;
}
@end
One of the data persistence