归档和解档
归档--encoder 它是将自定义的对象写入磁盘前将对象转成二进制然后存入磁盘。
解档--decoder 它是将磁盘上保存的二进制数据转换成自定义对象。
eg:
自定义一个person对象
.h 文件中
@property (nonatomic,copy)NSString *name;
@property (nonatomic,assign)int age;
.m 文件中
// 归档
- (void)encodeWithCode:(NSCode *)encode
{
[encode encodeObject:_name forKey:@"userName"];
[encode encodeInt:_age forKey:@"userAge"];
}
// 解档
-(instancetype)initWithCoder:(NSCoder *)decoder
{
if(self = [super init])
{
_name = [decoder decodeObjectForKey:@"userName"];
_age = [decoder decodeIntForKey:@"userAge"];
}
return self;
}
在控制器中调用
实例化一个person对象
Person *p = [[Person alloc]init];
p.name = @"Jerry";
p.age = 20;
// 解档
[NSKeyedArchiver archiveRootObject:p toFile:@"/Users/apple/Desktop/123.plist"];
// 解档
Person *p1 = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/apple/Desktop/123.plist"];
NSLog(@"%@",p1.name);