1, relevant knowledge points:
<1> types of objects that can be archived and recovered using Nskeyedarchiver: NSString, Nsdictionary, Nsarray, NSData, NSNumber, etc.
<2> use is the Nscoding protocol object that must be followed to implement two methods:
Encodewithcoder: This method is called when an object is archived.
Initwithcoder: This method is called every time an object is recovered from a file.
2. A simple example illustrates the detailed steps
<1> Create a student-to-like hustudent, follow the nscoding protocol, and give the student a set of three attributes:
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) double height;
@property (nonatomic, assign) int age;
<2> using the first method for storing data: Need to describe the properties that need to be stored
-(void) Encodewithcoder: (Nscoder *) encoder
{
[Encoder encodeObject:self.name forkey:@ "name"];
[Encoder encodeInt:self.age forkey:@ "age"];
[Encoder encodeDouble:self.height forkey:@ "height"];
}
<3> parse an object using the second method: Read Object properties
-(ID) Initwithcoder: (Nscoder *) decoder
{
if (self = [super init])
{
Self.name = [Decoder decoderobjectforkey:@ "name"];
Self.age = [Decoder decoderobjctforkey:@ "age"];
Self.height = [Decoder decoderobjectforkey:@ "height"];
}
return self;
}
<4> Assigning and reading model objects in the controller
>> property Assignment for model objects
//----1. the new Model object
Hustudent * student = [[Hustudent alloc]init];
Student.name = @ "Hulin";
Student.age = 24;
Student.height = 1.83;
-----2. Archiving Model objects
NSString * doc = [Nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes) Lastobject]; Get documents Full path
NSString * Path = [doc stringbyappendingpathcomponent:@ "Student.plist"]; Get the full path of a file
Nsarray * array = @[student];
[Nskeyedarchiver Archiverootobject:array Tofile:path]; Archive an Object
-----3. Read the properties of a model object
NSString * Doc =[nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes) lastObject]; Get documents Full path
NSString * Path = [doc stringbyappendingpathcomponent:@ "Student.plist"]; Get the full path of the file
Hustudent * student = [Nskeyedunarchiver Unarchiveobjectwithfile:path]; Reading an object from a file
NSLog (@ "%@,%d,%f", student.name,student.age,student.height);
3, the use of nskeyedarchiver storage data considerations:
If the subclass and parent class created in the program follow the Nscoding protocol, add [self encodewithcode:encode] to the Encodewithcoder: method (to ensure that the inherited instance variable can also be encoded); Initwithcoder: plus self = [super Initwithcoder:decoder] (ensure instance variables can also be decoded);