使用runtime字典转模型

2016-04-26  本文已影响88人  Juno_o
#import "NSObject+PropertyList.h"
#import <objc/runtime.h>
@implementation NSObject (PropertyList)

// 获取属性列表 在字典转模型的时候非常有用
+ (instancetype)objWithDict:(NSDictionary *)dict {
    id instance = [[self alloc]init];
    
    [[self propertys] enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        id value = dict[obj];
        if (value) {
            // 设置属性值
            [instance setValue:value forKey:obj];
        }
    }];
    return instance;
}
// copy, create,retain
+ (NSArray *)propertys {
    unsigned int count;// 表示属性个数
    // 获取到所有的属性
    objc_property_t *list = class_copyPropertyList(self, &count); // 数组
    NSMutableArray *data = [NSMutableArray array];
    for (int i = 0; i < count; ++i) {
        // 取出每一个属性
        objc_property_t key = list[i];
        // 转成字符串
        NSString *propertyName = [[NSString alloc]initWithCString:property_getName(key) encoding:NSUTF8StringEncoding];
        //        NSLog(@"%@",propertyName);
        [data addObject:propertyName];
    }
    // 释放list
    free(list);
    
    return data.copy;
}
上一篇 下一篇

猜你喜欢

热点阅读