ios通过Runtime动态完成数据存储(归档/解档)
实现数据序列化和反序列化,必定实现的两个方法:
- (void)encodeWithCoder:(NSCoder *)aCoder
{
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
}
return self;
}
当属性比较多的话,实现这两个方法属性要一个一个的写,做起来比较麻烦,但是通过runtime,就相当的简单,代码如下:
- (void)encodeWithCoder:(NSCoder *)encoder
{
unsigned int count = 0;
//通过runtime获取成员列表
Ivar *ivars = class_copyIvarList([Person 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 = [self valueForKey:key];
[encoder encodeObject:value forKey:key];
}
free(ivars);
}
- (id)initWithCoder:(NSCoder *)decoder
{
if (self = [super init]) {
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([Person 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 = [decoder decodeObjectForKey:key];
// 给成员变量赋值
[self setValue:value forKey:key];
}
free(ivars);
}
return self;
}
这样的话,不管有多少属性都能够一次性进行归档解档,相当方便。