首先要遵守NSCoding协议;
重写两个方法:
//归档属性
- (void)encodeWithCoder:(NSCoder *)coder
{
//归档!!
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];
//KVC
id value = [self valueForKey:KEY];
//归档
[coder encodeObject:value forKey:KEY];
}
//但凡在C语言里面 看到New Creat Copy 都需要释放
free(ivars);
}
//解档
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
unsigned int count = 0;
Ivar * ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
//名称
const char * name = ivar_getName(ivars[i]);
NSString * KEY = [NSString stringWithUTF8String:name];
//解档
id value = [coder decodeObjectForKey:KEY];
//设置到成员变量上
[self setValue:value forKey:KEY];
}
free(ivars);
}
return self;
}
网友评论