标签:
// 解档
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
unsigned int count;
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* strName = [NSString stringWithUTF8String:name];
id value = [aDecoder decodeObjectForKey:strName];
[self setValue:value forKey:strName];
}
free(ivars);
}
return self;
}
// 归档
- (void)encodeWithCoder:(NSCoder *)aCoder
{
unsigned int count;
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* strName = [NSString stringWithUTF8String:name];
id value = [self valueForKey:strName];
[aCoder encodeObject:value forKey:strName];
}
free(ivars);
}
头文件必须导入
#import <objc/runtime.h>
标签:
原文地址:http://www.cnblogs.com/fantasy3588/p/5557852.html