runtime获取所有的属性

2018-09-28  本文已影响3人  大胖_康

当一个Model类的属性很多的时候我们需要写很多重复的代码,因此我们就可以用runtime获取所有的属性

记住要导入 #import <objc/message.h>

1.序列化

//编码
- (void)encodeWithCoder:(NSCoder *)aCoder {
    //一般写法
//    [aCoder encodeObject:_name forKey:@"name"];
//    [aCoder encodeObject:@(_age) forKey:@"age"];
//    [aCoder encodeObject:_phone forKey:@"phone"];

    //runtime
    unsigned int count = 0;
    Ivar * ivars = class_copyIvarList([Person class], &count);//获取所以属性
    for (int i = 0; i< count; i++) {
        Ivar ivar = ivars[i];//属性名称
        const char * name = ivar_getName(ivar);
        NSString *key = [NSString stringWithUTF8String:name];//C-->OC
        id value = [self valueForKey:key];//取值
        [aCoder encodeObject:value forKey:key];
    }
    free(ivars);//释放
}

2.反序列化

//反编码
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]) {
        //一般写法
//        self.name = [aDecoder decodeObjectForKey:@"name"];
//        self.phone = [aDecoder decodeObjectForKey:@"phone"];
//        self.age = [[aDecoder decodeObjectForKey:@"age"] intValue];
        //runtime
        unsigned int count = 0;
        Ivar * ivars = class_copyIvarList([Person class], &count);//获取所以属性
        for (int i = 0; i< count; i++) {
            Ivar ivar = ivars[i];//属性名称
            const char * name = ivar_getName(ivar);
            NSString *key = [NSString stringWithUTF8String:name];//C-->OC
            id value = [aDecoder decodeObjectForKey:key];//取值
            [self setValue:value forKey:key];//赋值
        }
        free(ivars);//释放
        
    }
    return self;
}

使用

//归档
    Person *p1 = [[Person alloc]init];
    p1.name   =  @"SUN";
    p1.age    =  25;
    p1.phone =  @"110";
    [NSKeyedArchiver archiveRootObject:p1 toFile:[NSTemporaryDirectory() stringByAppendingPathComponent:@"person.data"]];
    //检测是否归档成功
    BOOL result = [[NSFileManager defaultManager] fileExistsAtPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"person.data"]];
    if (result) {
        NSLog(@"归档OK");
    }else{
        NSLog(@"归档NO");
    }

网络请求解析数据也经常用到

当然可以使用小码哥的 MJExtension
[Person mj_objectWithKeyValues:dict];

-(instancetype)initWithDic:(NSDictionary *)dic{
    if (self = [super init]) {
        //一般写法
//        self.name = dic[@"name"];
//        self.phone = dic[@"phone"];
//        self.age = [dic[@"age"] intValue];
        //runtime
        unsigned int count = 0;
        Ivar * ivars = class_copyIvarList([Person class], &count);//获取所以属性
        for (int i = 0; i< count; i++) {
            Ivar ivar = ivars[i];//属性名称
            const char * name = ivar_getName(ivar);
            NSString *key = [NSString stringWithUTF8String:name];//C-->OC
            id value = dic[[key substringFromIndex:1]];//取值
            [self setValue:value forKey:key];//赋值
        }
        free(ivars);//释放
    }
    return self;
    
}

基本上所有类似重复的代码都可以这种方式
Demo:https://github.com/Sunkangp/runtime

上一篇下一篇

猜你喜欢

热点阅读