02.实现NSCoding的自动归档和自动解档
解档
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]) {
Class c = self.class;
// 截取类和父类的成员变量
while (c && c != [NSObject class]) {
unsigned int count = 0;
Ivar *ivars = class_copyIvarList(c, &count);
for (int i = 0; i < count; i++) {
NSString *key = [NSString stringWithUTF8String:ivar_getName(ivars[i])];
id value = [aDecoder decodeObjectForKey:key];
if (value){// 容错
[self setValue:value forKey:key];
}
}
// 获得c的父类
c = [c superclass];
free(ivars);
}
}
return self;
}解档
Last updated