美文网首页
Runtime方式归档解档

Runtime方式归档解档

作者: sunshinesuns | 来源:发表于2016-09-19 17:34 被阅读10次
//归档
- (void)encodeWithCoder:(NSCoder *)aCoder{
unsigned int outCount = 0;
Ivar *ivars = class_copyIvarList([self class], &outCount);
for (unsigned int i =0; i<outCount; i++) {
  Ivar ivar = ivars[i];
  NSString*key = [NSString stringWithUTF8String:ivar_getName(ivar)];

  id value = [self valueForKey:key];
  [aCoder encodeObject:value forKey:key];
}
free(ivars);
}

//解归档
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{
  self = [super init];
  if (self) {
    unsigned int OutCount = 0;
    Ivar *ivars = class_copyIvarList([self class], &OutCount);
    for (unsigned int i =0; i<OutCount; i++) {
      Ivar ivar = ivars[i];
      NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
      [self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
    }
    free(ivars);
  }
  return  self;
}

相关文章

网友评论

      本文标题:Runtime方式归档解档

      本文链接:https://www.haomeiwen.com/subject/qssnettx.html