美文网首页
使用runtime机制归档与解档

使用runtime机制归档与解档

作者: 深夜爬坑 | 来源:发表于2017-08-11 16:16 被阅读0次

runtime的机制这里就不作详细述说,想要使用runtime机制了,说明你已经有了基础的认了。如果下面的代码封装成BaseModel,其他的Model都继承BaseModel,项目里的所有Model都可以很方便的使用归档与解档来存储数据了。

归档与解档

#import "Person.h"
// 调用runtime相关的函数,需要包含的头文件
#import<objc/message.h>

@implementation Person

//归档
- (void)encodeWithCoder:(NSCoder *)aCoder
{
   //获取成员变量数量
  unsigned int count = 0;
   //取出Person类的成员变量
  Ivar *ivars = class_copyIvarList([Person class], &count);
   //遍历所有的成员变量
  for (int i = 0; i < count; i++) {
    Ivar ivar = ivars[i];
      //获取成员变量的名
    NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
      //归档
    [aCoder encodeObject:[self valueForKey:key] forKey:key];
  }
  if (ivars != NULL) {
      //释放资源
    free(ivars);
  }
}

//解档
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
  self = [super init];
  if (self) {
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([Person class], &count);
    for (int i = 0; i < count; i++) {
      Ivar ivar = ivars[i];
          //同上
      NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
          //解档,获取key对应的值
      id value = [aDecoder decodeObjectForKey:key];
          //给成员变量赋值
      [self setValue:value forKey:key];
    }
  }
  if (ivars != NULL) {
      //释放资源
    free(ivars);
  }
        return self;
}

相关文章

网友评论

      本文标题:使用runtime机制归档与解档

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