Runtime 自动化归档

时间:2024-08-28 21:07:26

Runtime的使用

 (id)initWithCoder:(NSCoder *)decoder
{
  if (self = [super init]) {
  unsigned int count = ;
  Ivar *ivars = class_copyIvarList([self class], &count);   for (int i = ; 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;
}
 - (void)encodeWithCoder:(NSCoder *)encoder
{ unsigned int count = ;
Ivar *ivars = class_copyIvarList([self class], &count); for (int i = ; 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);
}