// 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.获取文件路径
NSString * docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory , NSUserDomainMask , YES) lastObject];
//尾加文件名
NSString * path = [docPath stringByAppendingString:@"guoyule.arc"];
NSLog(@"path = %@",path);
// 3.将自己定义的对象保存到文件中
[NSKeyedArchiver archiveRootObject:stu toFile:path];
}
- (IBAction)readBtn:(id)sender {
NSString * docPth = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask,YES) lastObject];
NSString * path = [docPth stringByAppendingString:@"guoyule.arc"];
// 2.从文件中读取对象
GYLStudent * guo = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"%@,%d,%.1f,%@",guo.name,guo.age,guo.hight,guo.email);
}
在使用继承的时候 一定要让父类使用 [super encodeWithCoder:aCoder];
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[super encodeWithCoder:aCoder];
NSLog(@"GYLStudent encodeWithCoder");
[aCoder encodeObject:self.email forKey:@"email"];
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) {
NSLog(@"GYLStudent initWithCoder");
self.email = [aDecoder decodeObjectForKey:@"email"];
}
return self;
}