利用runtime归解档

- (instancetype)initWithCoder:(NSCoder *)aDecoder {

if (self = [super init]) {

unsigned int count = 0;

//获取类中所有成员变量名

Ivar *ivar = class_copyIvarList([self class], &count);

for (int i = 0; i < count; i++) {

Ivar iva = ivar[i];

const char *name = ivar_getName(iva);

NSString *strName = [NSString stringWithUTF8String:name];

//进行解档取值

id value = [aDecoder decodeObjectForKey:strName];

//利用KVC对属性赋值

[self setValue:value forKey:strName];

}

free(ivar);

}

return self;

}

- (void)encodeWithCoder:(NSCoder *)aCoder {

unsigned int count;

Ivar *ivar = class_copyIvarList([self class], &count);

for (int i = 0; i < count; i++) {

Ivar iv = ivar[i];

const char *name = ivar_getName(iv);

NSString *strName = [NSString stringWithUTF8String:name];

//利用KVC取值

id value = [self valueForKey:strName];

[aCoder encodeObject:value forKey:strName];

}

free(ivar);

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,786评论 0 9
  • 对于从事 iOS 开发人员来说,所有的人都会答出【runtime 是运行时】什么情况下用runtime?大部分人能...
    梦夜繁星阅读 3,733评论 7 64
  • OC最实用的runtime总结,面试、工作你看我就足够了! 前言runtime的资料网上有很多了,部分有些晦涩难懂...
    small_Sun阅读 937评论 1 12
  • Runtime是一套比较底层的纯C语言API,包含了很多底层的C语言API。在我们平时编写的OC代码中,程序运行时...
    这个年纪的情愫丶阅读 633评论 5 3
  • 兴冲冲跑去花卉市场买过几盆花草回来,种下天天浇水、期待开花的心。 然而,死去的很快,期待消失的更快。 于是,买鲜花...
    恭煮阅读 297评论 0 0