- (instancetype)jy_initWithCoder:(NSCoder *)aDecoder
{
if (!aDecoder) return self;
if (self == (id)kCFNull) return self;
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
//取出i对应位置的成员变量
Ivar ivar = ivars;
//查看成员变量
const char *name = ivar_getName(ivar);
//归档
NSString *key = [NSString stringWithUTF8String:name];
id value = [aDecoder decodeObjectForKey:key];
//设置到成员变量身上
[self setValue:value forKey:key];
}
free(ivars);
return self;
}
- (void)jy_encodeWithCoder:(NSCoder *)aCoder
{
if (!aCoder) return;
if (self == (id)kCFNull) {
[((id<NSCoding>)self)encodeWithCoder:aCoder];
return;
}
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivars;
const char *name = ivar_getName(ivar);
NSString *key = [NSString stringWithUTF8String:name];
id value = [self valueForKey:key];
[aCoder encodeObject:value forKey:key];
}
free(ivars);
}