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
推荐阅读
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- MybatisPlus使用queryWrapper如何实现复杂查询
- python学习之|python学习之 实现QQ自动发送消息
- 孩子不是实现父母欲望的工具——林哈夫
- opencv|opencv C++模板匹配的简单实现
- Node.js中readline模块实现终端输入
- java中如何实现重建二叉树
- 人脸识别|【人脸识别系列】| 实现自动化妆
- paddle|动手从头实现LSTM
- pytorch|使用pytorch从头实现多层LSTM