一. 归档方法
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *phone;
在 person 类的. m 实现归档解档的方法
// 转码
- (void) encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"pName"];
[aCoder encodeObject:self.phone forKey:@"pPhone"];
}
// 反转码
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
// 把编号的数据, 反编码到本身的属性上
self.name = [aDecoder decodeObjectForKey:@"pName"];
self.phone = [aDecoder decodeObjectForKey:@"pPhone"];
}
return self;
}
// 第一步:有一个遵守 NSCoding 协议的复杂对象
Person *person = [[Person alloc]init];
person.name = @"张三";
person.phone = @"123123123123123";
// 需要遵循 NSCoding 协议 在 person 类里面遵守
// 创建归档工具
// 将 person 类进行编码到 mutabaleData 里面
NSMutableData *personData = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:personData];
// 将 person 类编码到 personData 里面
[archiver encodeObject:person forKey:@"person"];
// 结束编码
[archiver finishEncoding];
NSLog(@"%@", personData);
// 写到哪里 初始化一个路径
NSString *path = [documentStr stringByAppendingPathComponent:@"/person.txt"];
// 写入本地
[personData writeToFile:path atomically:YES];
NSData *data = [NSData dataWithContentsOfFile:path];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
Person *person1 = [unarchiver decodeObjectForKey:@"person"];
[unarchiver finishDecoding];
NSLog(@"person1 ==== %@", person1.name);
归解档的简单写法
Person *persons = [[Person alloc]init];
persons.name = @"李四";
persons.phone = @"23232323232";
// 归档方法
NSString *paths = [documentStr stringByAppendingPathComponent:@"/newPerson.txt"];
[NSKeyedArchiver archiveRootObject:persons toFile:paths];
// 解档方法
Person *persons1 = [NSKeyedUnarchiver unarchiveObjectWithFile:paths];
NSLog(@"person1 ==== %@", persons1.name);