• 用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;
    }
    
  • 相关阅读:
    资源-python 视频下载大全
    ubuntu 16.04(操作应用) -软件卸载
    资源-简历的相关知识
    centos (命令操作)-crontab命令
    ubuntu 16.04 (软件应用)-输入法
    ntp时间同步
    lvm空间扩容
    目录知识
    Linux下安装maven
    elasticsearch安装pinyin模块
  • 原文地址:https://www.cnblogs.com/damiao/p/5358538.html
Copyright © 2020-2023  润新知