本文主要是介绍归档/解档,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一. 归档方法
@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);
这篇关于归档/解档的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!