字典转模型
重中之重!
好多解析model 的框架底层原理都是基于runtime
1.动态添加属性代码
{
"classNum": "3年二班",
"user": [
{"name":"张三"
"age":22
},
{"name":"李四"
"age":34
},
]
"isHave":YES
"totol":2
}
建一个NSDictionary 分类
- (void)createPropertyWithDict{
NSMutableString *string = [NSMutableString string];
[self enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:[NSString class]]) {
NSString* str = [NSString stringWithFormat"@property (nonatomic,strong) NSString *%@;",key];
[string appendFormat"\n%@\n",str];
}else if ([obj isKindOfClass:[NSArray class]]){
NSString* str = [NSString stringWithFormat"@property (nonatomic,strong) NSArray *%@;",key];
[string appendFormat"\n%@\n",str];
}else if ([obj isKindOfClass:[NSDictionary class]]){
NSString* str = [NSString stringWithFormat"@property (nonatomic,strong) NSDictionary *%@;",key];
[string appendFormat"\n%@\n",str];
}else if ([obj isKindOfClass:NSClassFromString(@"__NSCFBoolean")]){
NSString* str = [NSString stringWithFormat"@property (nonatomic,assign) BOOL %@;",key];
[string appendFormat"\n%@\n",str];
}else if ([obj isKindOfClass:[NSNumber class]]){
NSString* str = [NSString stringWithFormat"@property (nonatomic,assign) NSInteger %@;",key];
[string appendFormat"\n%@\n",str];
}
}];
NSLog(@"%@",string);
}
然后用字典直接调用createPropertyWithDict
得到结果如下
@property (nonatomic,assign) NSInteger totole;
@property (nonatomic,strong) NSString * classNum;
@property (nonatomic,assign) BOOL isHave;
@property (nonatomic,strong) NSArray *user;
2.字典转model
- (id)modelWithDictNSDictionary*)dict{
NSObject *obj = [[[self class] alloc] init];
unsigned int count = 0;
//之所以用class_copyIvarList 而不用 class_copyPropertyList,因为我们可能忽略成员变量,但不会忽略属性
Ivar *IvalList = class_copyIvarList([self class], &count);
for (int i = 0; i<count; i++) {
Ivar ivar = IvalList[i];
//ivar_getName(ivar) 得到成员变量的名字
//c语言字符串转oc字符串转
NSString *ivarStr = [NSString stringWithUTF8String:ivar_getName(ivar)];
ivarStr = [ivarStr substringFromIndex:1];
//ivar_getTypeEncoding(ivar) 得到成员变量的类型
NSString *ivarType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
ivarType = [ivarType stringByReplacingOccurrencesOfString:@"@" withString:@""];
ivarType = [ivarType stringByReplacingOccurrencesOfString:@"\"" withString:@""];
[obj setValue:dict[ivarStr] forKey:ivarStr];
}
return obj;
} |