三、字典数组 to 模型
#pragma mark - 复杂字典 转 模型
- (void)keyValuesArrayToObject {
// 1.定义一个字典数组
NSArray *dictArray = @[
@{
@"name" : @"Jack",
@"icon" : @"lufy.png",
},
@{
@"name" : @"Rose",
@"icon" : @"nami.png",
}
];
}
在 NSObject+Extension.m 文件中添加方法+ objectArrayFromKeyValuesArray:
+ (NSMutableArray *)objectArrayFromKeyValuesArray:(NSArray *)keyValuesArray {
// 1.创建数组
NSMutableArray *modelArray = [NSMutableArray array];
// 2.遍历传进来的字典数组
for (NSDictionary *keyValues in keyValuesArray) {
if ([keyValues isKindOfClass:[NSArray class]]) {
[modelArray addObject:[self objectArrayFromKeyValuesArray:(NSArray *)keyValues]];
}
else {
id model = [self objectFromKeyValue:keyValues];
if (model) {
[modelArray addObject:model];
}
}
}
return modelArray;
}
回到ViewController 在字典数组下面
NSArray *modelArr = [YLUserModel objectArrayFromKeyValuesArray:dictArray];
for (YLUserModel *user in modelArr) {
NSLog(@"name = %@",user.name);
}
字典数组 to 模型 的输出.png
四、用自定义的属性名接收key
#pragma mark - 用自定义的属性名接收key
- (void)keyValuesArrayToObjectReplace {
// 1.定义一个字典
NSDictionary *dict = @{
@"id" : @"20",
@"desciption" : @"好孩子",
@"name" : @"Jack",
};
}
// 在模型里实现协议
+ (NSDictionary *)replacedKeyFromPropertyName {
return @{
@"ID" : @"id",
@"desc" : @"desciption"
};
}
修改 + objectFromKeyValue: 方法
+ (instancetype)objectFromKeyValue:(NSDictionary*)keyValue {
id obj = [[self alloc]init];
unsigned int count;
// 获取成员变量数组:注意:只会获取当前类的属性,不会获取父类
Ivar *ivarList = class_copyIvarList(self, &count);
// 遍历
for (int i = 0; i < count; i++) {
Ivar ivar = ivarList[i];
// 获取成员变量名字
NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)];
//NSLog(@"ivarName = %@",ivarName);//_age _name _icon _height _money
// 截取 - 获得模型的属性名
NSString *modelProperty = [ivarName substringFromIndex:1];
//NSLog(@"modelProperty = %@",key);//age name icon height money
NSString *keyBeReplaced; // 判断是否要被替换 不判断会死
if ([self respondsToSelector:@selector(replacedKeyFromPropertyName)]) {
keyBeReplaced = [self replacedKeyFromPropertyName][modelProperty];
}
// 获取字典里的值 (判断是否是被替换的)
id value;
if (keyBeReplaced) {
value = keyValue[keyBeReplaced];
}
else{
value = keyValue[modelProperty];
}
// 复杂字典,里面还有字典
// 所以要获取成员变量的类型
NSString *ivarType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
// @\"YLUserModel\" 需要截取 ,否则下面的 secIvarClass 是不存在的(这里要好好看下MJExtension,这个解决方式比较low)
ivarType = [ivarType stringByReplacingOccurrencesOfString:@"@" withString:@""];
ivarType = [ivarType stringByReplacingOccurrencesOfString:@"\"" withString:@""];
//NSLog(@"ivarType = %@",ivarType);
if ([value isKindOfClass:[NSDictionary class]] && ![ivarType hasPrefix:@"NS"]) {
Class secIvarClass = NSClassFromString(ivarType);
value = [secIvarClass objectFromKeyValue:value];
NSLog(@"");
}
// 赋值
[obj setValue:value forKey:modelProperty];
}
return obj;
}
回到ViewController 在字典下面
YLUserModel *user = [YLUserModel objectFromKeyValue:dict];
NSLog(@"name = %@,ID = %@,desc = %@",user.name,user.ID,user.desc);
用自定义的属性名接收key 的输出.png
今天到此结束,下次的是字典里有数组,数组里又有字典的情况
网友评论