RunTime与快速字典转模型(KVC)
-
运用场景:说道字典字典转模型属性,有时候模型属性非常多的时候应用这个知识比一个一个来写快的多。
方式一:快速字典转模型(KVC)
.h文件
#################### .h文件 ####################
// NSObject+Log.h
// 05-字典转模型(KVC)
// Created by ming on 16/1/12.
// Copyright © 2016年 ming. All rights reserved.
#import <Foundation/Foundation.h>
@interface NSObject (Log)
+ (void)resolveDict:(NSDictionary *)dict;
@end```
# .m文件
#################### .m文件 ####################
// NSObject+Log.m
// 05-字典转模型(KVC)
// Created by ming on 16/1/12.
// Copyright © 2016年 ming. All rights reserved.
import "NSObject+Log.h"
@implementation NSObject (Log)
// 自动打印属性字符串
-
(void)resolveDict:(NSDictionary *)dict{
// 拼接属性字符串代码
NSMutableString *strM = [NSMutableString string];// 1.遍历字典,把字典中的所有key取出来,生成对应的属性代码
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {// 类型经常变,抽出来 NSString *type; if ([obj isKindOfClass:NSClassFromString(@"__NSCFString")]) { type = @"NSString"; }else if ([obj isKindOfClass:NSClassFromString(@"__NSCFArray")]){ type = @"NSArray"; }else if ([obj isKindOfClass:NSClassFromString(@"__NSCFNumber")]){ type = @"int"; }else if ([obj isKindOfClass:NSClassFromString(@"__NSCFDictionary")]){ type = @"NSDictionary"; }else if ([obj isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) { type = @"BOOL"; } // 属性字符串 NSString *str; if ([type hasPrefix:@"NS"]) { str = [NSString stringWithFormat:@"@property (nonatomic, strong) %@ *%@;",type,key]; }else if([type hasPrefix:@"Bo"]) { str = [NSString stringWithFormat:@"@property (nonatomic, assign) %@ %@;",type,key]; }else{ str = [NSString stringWithFormat:@"@property (nonatomic, assign) %@ %@;",type,key]; } // 每生成属性字符串,就自动换行。 [strM appendFormat:@"\n%@\n",str];
}];
// 把拼接好的字符串打印出来,就好了。
NSLog(@"%@",strM);
}
@end
#模型
#################### Status.h ####################
// Status.h
// 05-字典转模型(KVC)
// Created by ming on 16/1/12.
// Copyright © 2016年 ming. All rights reserved.
import <Foundation/Foundation.h>
@interface Status : NSObject
/** 字典转模型 */
- (instancetype)statusWithDict:(NSDictionary *)dict;
@end
#################### Status.m ####################
// Status.m
// 05-字典转模型(KVC)
import "Status.h"
@implementation Status
/** 字典转模型 */
-
(instancetype)statusWithDict:(NSDictionary *)dict{
Status *status = [[Status alloc] init];[status setValuesForKeysWithDictionary:dict];
return status;
}
@end
#控制器
#################### .控制器文件 ####################
// ViewController.m
// 05-字典转模型(KVC)
import "ViewController.h"
import "NSObject+Log.h"
import "Status.h"
@interface ViewController ()
/** <#注释#> */
@property (nonatomic,strong) NSMutableArray *statuses;
@end
@implementation ViewController
-
(void)viewDidLoad {
[super viewDidLoad];// 解析Plist文件
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"status.plist" ofType:nil];NSDictionary *statusDict = [NSDictionary dictionaryWithContentsOfFile:filePath];
// 获取字典数组
NSArray *dictArr = statusDict[@"statuses"];_statuses = [NSMutableArray array];
// 遍历字典数组
for (NSDictionary *dict in dictArr) {// 自动生成模型属性字符串 [NSObject resolveDict:dict]; // Status *status = [Status statusWithDict:dict]; // [_statuses addObject:status];
}
}
@end```
-
结果:快速转化成了属性


方式二:RunTime
思路:利用运行时,遍历模型中所有属性,根据模型的属性名,去字典中查找key,取出对应的值,给模型的属性赋值。
-
步骤:提供一个NSObject分类,专门字典转模型,以后所有模型都可以通过这个分类转。
-
详细步骤:见代码
#import <Foundation/Foundation.h>
@protocol ModelDelegate <NSObject>@optional
// 提供一个协议,只要准备这个协议的类,都能把数组中的字典转模型、、用在三级数组转换
+ (NSDictionary *)arrayContainModelClass;
@end
@interface NSObject (Item)
// 字典转模型
+ (instancetype)objectWithDict:(NSDictionary *)dict;
@end```
import "NSObject+Item.h"
import <objc/message.h>
@implementation NSObject (Item)
/** 把字典中所有value给模型中属性赋值,
- KVC:遍历字典中所有key,去模型中查找
- Runtime:根据模型中属性名去字典中查找对应value,如果找到就给模型的属性赋值.
*/
// 字典转模型
-
(instancetype)objectWithDict:(NSDictionary *)dict{
// 创建对应模型对象
id objc = [[self alloc] init];
unsigned int count = 0;// 1.获取成员属性数组
Ivar *ivarList = class_copyIvarList(self, &count);// 2.遍历所有的成员属性名,一个一个去字典中取出对应的value给模型属性赋值
for (int i = 0; i < count; i++) {
// 2.1 获取成员属性
Ivar ivar = ivarList[i];
// 2.2 获取成员属性名 C -> OC 字符串
NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)];
// 2.3 _成员属性名 => 字典key
NSString *key = [ivarName substringFromIndex:1];
// 2.4 去字典中取出对应value给模型属性赋值
id value = dict[key];
// 获取成员属性类型
NSString *ivarType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
##############################################二级转换###################################################
// 二级转换,字典中还有字典,也需要把对应字典转换成模型
// // 判断下value,是不是字典
if ([value isKindOfClass:[NSDictionary class]] && ![ivarType containsString:@"NS"]) {
// 是字典对象,并且属性名对应类型是自定义类型
// user User
// 处理类型字符串 @"User" -> User
ivarType = [ivarType stringByReplacingOccurrencesOfString:@"@" withString:@""];
ivarType = [ivarType stringByReplacingOccurrencesOfString:@""" withString:@""];
// 自定义对象,并且值是字典
// value:user字典 -> User模型
// 获取模型(user)类对象
Class modalClass = NSClassFromString(ivarType);
// 字典转模型
if (modalClass) {
// 字典转模型
user value = [modalClass objectWithDict:value];
}
// 字典,user
// NSLog(@"%@",key);
}
##############################################三级转换###################################################
// 三级转换:NSArray中也是字典,把数组中的字典转换成模型.
// 判断值是否是数组
if ([value isKindOfClass:[NSArray class]]) {
// 判断对应类有没有实现字典数组转模型数组的协议
if ([self respondsToSelector:@selector(arrayContainModelClass)]) {
// 转换成id类型,就能调用任何对象的方法
id idSelf = self;
// 获取数组中字典对应的模型
NSString *type = [idSelf arrayContainModelClass][key];
// 生成模型
Class classModel = NSClassFromString(type);
NSMutableArray *arrM = [NSMutableArray array];
// 遍历字典数组,生成模型数组
for (NSDictionary *dict in value) {
// 字典转模型
id model = [classModel objectWithDict:dict];
[arrM addObject:model];
}
// 把模型数组赋值给
value value = arrM;
}
}
// 2.5 KVC字典转模型
if (value) {
[objc setValue:value forKey:key];
}
}
// 返回对象
return objc;}@end
}
***
######模型代码
import <Foundation/Foundation.h>
import "NSObject+Item.h"
@class User;@interface Status :NSObject <ModelDelegate>
@property (nonatomic, strong) NSString *source;
@property (nonatomic, assign) int reposts_count;
@property (nonatomic, strong) NSArray *pic_urls;
@property (nonatomic, strong) NSString *created_at;
@property (nonatomic, assign) int attitudes_count;
@property (nonatomic, strong) NSString *idstr;
@property (nonatomic, strong) NSString *text;
@property (nonatomic, assign) int comments_count;
@property (nonatomic, strong) User *user;
@end```
#import "Status.h"
@implementation Status
+ (NSDictionary *)arrayContainModelClass {
return @{ @"pic_urls" : @"Picture" };
}
@end```