什么是归档?什么是解档?
归档:就是把对象序列化,序列化就是把对象写到一个指定的app路径下的文件里,app有三个目录分别是:docments、library、tmp,也叫做对象的持久化,ios开发中一般的持久化不支持自定义对象的持久化,归档解档就可以完成自定义对象的持久化。
实现归档解档的步骤:
Step1:要实现对象的归档解档首先继承Coding协议(protocol)
Step2:实现两个方法:encodeWihtCoder: 和 initWithCoder:
runtime实现方法 少写很多的给属性赋值的方法
//归档
- (void)encodeWithCoder:(NSCoder*)aCoder
{
NSLog(@"归档encodeWithCoder方法调用了");
unsigned int count = 0;
Ivar* ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivars[i];
const char* name = ivar_getName(ivar);
NSString* key = [NSString stringWithUTF8String:name];
[aCoder encodeObject:[self valueForKey:key] forKey :key];
}
free(ivars);
}
//解档
- (id)initWithCoder:(NSCoder*)aDecoder
{
NSLog(@"解档initWithCoder方法调用了");
if (self == [super init]) {
unsigned int count = 0;
Ivar* ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivars[i];
const char* name = ivar_getName(ivar);
NSString* key = [NSString stringWithUTF8String:name];
id value = [aDecoder decodeObjectForKey:key];//根据key拿到value
[self setValue:value forKey:key];//KVC赋值
}
free(ivars);
}
return self;
}
使用: 归档
//获取文件目录
NSString* docPatn = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//NSString* homePath = NSTemporaryDirectory();
NSLog(@"docPath = %@",docPatn);
NSLog(@"homePath = %@",homePath);
NSString* path = [docPatn stringByAppendingPathComponent:@"zht.hank"];
//自定义对象存到文件中
[NSKeyedArchiver archiveRootObject:person toFile:path];
解档:
ZHTPerson* p = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"name = %@,age = %d",p.name,p.age);