「这是我参与2022首次更文挑战的第25天,活动详情查看:2022首次更文挑战」。
- 本文主要介绍在iOS开发中使用
runtime自动生成属性。
1. 自动生成属性
我们在实际开发中,通常会根据服务端返回的数据,生成我们对应的属性。
但是如果我们自己写的话就比较复杂,因此我们可以根据字典中的属性的类型我们进行拼接生成对应的属性。
-(void)crateAutoProperty{
NSMutableString *propertys = [NSMutableString string];
[self enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull value, BOOL * _Nonnull stop) {
NSString *property = nil;
if ([value isKindOfClass:[NSString class]]) {
property = [NSString stringWithFormat:@"@property (nonatomic, strong) NSString *%@;",key];
} else if ([value isKindOfClass:NSClassFromString(@"__NSCFBoolean")]){
property = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;",key];
} else if ([value isKindOfClass:[NSNumber class]]) {
property = [NSString stringWithFormat:@"@property (nonatomic, assign) NSInteger %@;",key];
} else if ([value isKindOfClass:[NSArray class]]) {
property = [NSString stringWithFormat:@"@property (nonatomic, strong) NSArray *%@;",key];
} else if ([value isKindOfClass:[NSDictionary class]]) {
property = [NSString stringWithFormat:@"@property (nonatomic, strong) NSDictionary *%@;",key];
}
// 拼接字符串
[propertys appendFormat:@"%@\n",property];
}];
NSLog(@"%@",propertys);
}
我们在字典的分类中添加这个方法用于打印当前字典中拼接的属性。这里对于BooL值我们是无法手动打印出来他的类型,是一个私有的API我们可以通过NSClassFromString(@"__NSCFBoolean")表达出来。
BooL值也是NSNumber的子类,我们因此要先判断BOOL类型。这里使用isKindOfClass,通过当前类的继承连递归进行查找是否存在。
中间可能会有一些易漏比如null的情况,我们根据实际开发需要进行修改Float,Double等。
2.字典转模型
在开发中,我们经常会使用YYModel或者MJModel等三方的model进行转换,那么他们是怎么实现的。
继续看下YYModelMeta的实现
会设置一些白名单和黑名单的属性,modelContainerPropertyGenericClass则是我们对于一些嵌套使用。
之后去除我们设置的黑名单或者白名单,获取所有的属性。
之后在字典中取出对应的值进行匹配赋值。
总体思路就是runtime遍历模型中属性,去字典中取出对应value,在给模型中属性赋值。