将对象归档到本地文件
归档的过程就是数据编码的过程
解档的过程就是反编码的过程
编码:person对象--->NSData对象
要进行归档必须遵守协议(NSCoding)
先对属性编码,再对person对象编码(由内向外)
Person.h
@interface Person:NSObject<NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *sex;
Person.m
//解档时,系统会自动调用该方法初始化对象
- (id)initWithCoder:(NSCoder*)aDecoder{
self = [super init];
if(self){
_name = [aDecoder decodeObjectForKey:@"name";
_age = [aDecoder decodeObjectForKey:@"age";
_sex = [aDecoder decodeObjectForKey:@"sex";
}
return self;
}
//归档时,系统会自动调用该方法
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeObject:_age forKey:@"age"];
[aCoder encodeObject:_sex forKey:@"sex"];
}
main.m
Person *person = [[Person alloc]init];
person.name = @"xiaohong";
person.age = 18;
person.name = @"female";
//将对象归档
NSData *personData = [NSKeyArchiver crchiveredDataWithRootObject:person];
//写入本地文件(如果看看结构,可以该后缀名.plist)
[personData writeToFile:@"路径名/文件名.plist" atomically:YES];
//解档 把文件转为Data对象
NSData *personData = [NSData dataWithContentOfFile:@"文件"];
Person *person1 = [NSKeyUnarchiver unarchiverObjectWithData:person1Data];
//多个对象归档
Person *person2 = [[Person alloc]init];
person.name = @"xuaihong";
person.age = 20;
person2.sex = @"male";
NSDictionary *dict = @{@"name" : @"Tom"};
//把对象转换成data
NSMutableData *data = [NSMutableData data];
//生成归档对象,归档开始
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
//data是编码后的对象数据的容器,开始归档后,调用
encodeObject: forKey: //系统自动把转码后的数据传入data
[archiver encodeObject:person2 forKey:@"person"];
//编码字典对象
[archiver encodeObject:dict forKey:@"dict"];