Archive and archive data access
-(IBAction) savebtn :( id) sender {
// GYLPerson * p = [[GYLPerson alloc] init];
// P. name = @ "guoyule ";
// P. age = 24;
// P. hight = 178.0f;
GYLStudent * stu = [[GYLStudent alloc] init];
Stu. name = @ "guoyule ";
Stu. age = 24;
Stu. hight = 178.0f;
Stu. email = @ "guoyulehit@icloud.com ";
// 2. Obtain the file path
NSString * docPath = [NSSearchPathForDirectoriesInDomains (NSDocumentationDirectory, NSUserDomainMask, YES) lastObject];
// Append the file name
NSString * path = [docPath stringByAppendingString: @ "guoyule. arc"];
NSLog (@ "path = % @", path );
// 3. Save the defined object to the file
[NSKeyedArchiver archiveRootObject: stu toFile: path];
}
-(IBAction) readBtn :( id) sender {
NSString * docPth = [NSSearchPathForDirectoriesInDomains (NSDocumentationDirectory, NSUserDomainMask, YES) lastObject];
NSString * path = [docPth stringByAppendingString: @ "guoyule. arc"];
// 2. Read objects from files
GYLStudent * guo = [NSKeyedUnarchiver unarchiveObjectWithFile: path];
NSLog (@ "% @, % d, %. 1f, % @", guo. name, guo. age, guo. hight, guo. email );
}
When using inheritance, make sure that the parent class uses [super encodeWithCoder: aCoder];
@ Class GYLStudent, GYLPerson;
-(Void) encodeWithCoder :( NSCoder *) ACO
{
[Super encodeWithCoder: aCoder];
NSLog (@ "GYLStudent encodeWithCoder ");
[Ecoder encodeObject: self. email forKey: @ "email"];
}
-(Id) initWithCoder :( NSCoder *) aDecoder
{
If (self = [super initWithCoder: aDecoder]) {
NSLog (@ "GYLStudent initWithCoder ");
Self. email = [aDecoder decodeObjectForKey: @ "email"];
}
Return self;
}