用runtime来重写Coder和deCode方法 归档解档的时候使用

当我们归档自定义对象的时候,可以重写自定义Model的的encodeWithCoder和initWithCoder

开始的大概是这样的,当属性非常多的时候 这种方式就会觉得不还好 好像重复在做一样的事情 其实这块我们可以交给runtime来做

- (void)encodeWithCoder:(NSCoder *)aCoder //将属性进行编码
{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.phone forKey:@"phone"];
    [aCoder encodeInteger:self.age forKey:@"age"];   
}
- (id)initWithCoder:(NSCoder *)aDecoder //将属性进行解码
{
    NSString *name1 = [aDecoder decodeObjectForKey:@"name"];
    NSString *phone1 = [aDecoder decodeObjectForKey:@"phone"];
    int age1 = [aDecoder decodeIntegerForKey:@"age"];
    [self initWithName:name1 phone:phone1 age:age1];    
    return self;
}

 

用runtime来实现上面的功能

-(void)encodeWithCoder:(NSCoder *)encoder{
    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];
        [encoder encodeObject:value forKey:strName];
    }
    free(ivar);
}

-(id)initWithCoder:(NSCoder *)decoder{
    self  = [super init];
    if (self) {
        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 = [decoder decodeObjectForKey:strName];
            //利用KVC对属性赋值
            [self setValue:value forKey:strName];
        }
        free(ivar);
    }
    return self;
}

 

转载于:https://www.cnblogs.com/damiao/p/5358538.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值