Runtime实现字典转模型

导言:开发过程中可能需要根据字典(NSDictionary)转换成模型(Model),而Model一般都是用户自定义的类继承自NSObject,所以可以对NSObject新建一个分类(Category)。
【Runtime实现字典转模型】分析:一般Model可能有多个存储属性,而字典中存储的也是多个键值对key-value),所以需要对遍历Model的属性,然后比对字典中的key,如果key和属性的名称相同,则通过KVC的方式将该value赋值给该属性。遍历Model的属性数组,就可以使用Runtime的方式取出该类的属性。
代码:

  • .h文件
#import @interface NSObject (LSHExtension)/** 字典转模型 @param dic 字典 @return instancetype */ + (instancetype)objWithDic:(NSDictionary *)dic; @end

  • .m文件
#import "NSObject+LSHExtension.h" #import @implementation NSObject (LSHExtension)+ (instancetype)objWithDic:(NSDictionary *)dic {id object = [[self alloc] init]; NSArray *propertyList = [self getProperties]; //遍历字典的所有的key [dic enumerateKeysAndObjectsUsingBlock:^(id_Nonnull key, id_Nonnull obj, BOOL * _Nonnull stop) { //属性中有该字典中的key,才可以赋值 if ([propertyList containsObject:key]) { [object setValue:obj forKey:key]; } }]; return object; }+ (NSArray *)getProperties { //存储所有的property的名称 NSMutableArray *propertyNames = [NSMutableArray array]; //属性个数 unsigned int count = 0; //通过Runtime获取当前类的所有属性 objc_property_t *properties = class_copyPropertyList([self class], &count); //遍历所有的属性,获取所有的属性名称 for (int i = 0; i < count; i ++) {objc_property_t property = properties[i]; const char * propertyName = property_getName(property); [propertyNames addObject:[NSString stringWithUTF8String:propertyName]]; } //释放 free(properties); return propertyNames; }@end

    推荐阅读