话不多说 看代码
#import <Foundation/Foundation.h>
@protocol NSObjectDelegate <NSObject>
// 提供一个协议,只要准备这个协议的类,都能把数组中的字典转模型
+ (NSDictionary *)arrayContainModelClass;
@end
@interface NSObject (Category)
+ (instancetype)initWithDict:(NSDictionary *)dict;
@end
// NSObject+Category.m
// RunTimeTest
// Created by tuhaisheng on 17/3/7.
// Copyright © 2017年 tuhaisheng. All rights reserved.
#import "NSObject+Category.h"
#import "objc/runtime.h"
@implementation NSObject (Category)
+ (instancetype)initWithDict:(NSDictionary *)dict{
id objc = [[self alloc] init];
unsigned int count;
//获取类中的所有成员属性
Ivar * ivarList = class_copyIvarList(self, &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivarList[i];
//获取成员属性名
NSString * name = [NSString stringWithUTF8String:ivar_getName(ivar)];
NSLog(@"===name===%@=====",name);
NSString * key = [name substringFromIndex:1];
id value = dict[key];
//value 是否是字典
if ([value isKindOfClass:[NSDictionary class]]) {
//获取成员属性类型
NSString * type = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
NSRange range = [type rangeOfString:@"\""];
type = [type substringFromIndex:range.location + range.length];
range = [type rangeOfString:@"\""];
// 裁剪到哪个角标,不包括当前角标
type = [type substringToIndex:range.location];
// 根据字符串类名生成类对象
Class modelClass = NSClassFromString(type);
if (modelClass) {
value = [modelClass initWithDict:value];
}
}
if ([value isKindOfClass:[NSArray class]]) {
if ([self respondsToSelector:@selector(arrayContainModelClass)]) {
//
id idSelf = self;
NSString *type = [idSelf arrayContainModelClass][key];
// 生成模型
Class classModel = NSClassFromString(type);
NSMutableArray *arrM = [NSMutableArray array];
// 遍历字典数组,生成模型数组
for (NSDictionary *dict in value) {
// 字典转模型
id model = [classModel initWithDict:dict];
[arrM addObject:model];
}
// 把模型数组赋值给value
value = arrM;
}
}
if (value) { // 有值,才需要给模型的属性赋值
// 利用KVC给模型中的属性赋值
[objc setValue:value forKey:key];
}
}
return objc;
}
@end
不管是字典里面包含数组还是字典,都会以 [objc setValue:value forKey:key];来执行。
arrayContainModelClass 这个是一个协议,只要准备这个协议的类,都能把数组中的字典转模型
+ (NSDictionary *)arrayContainModelClass{
return @{@"person":@"Person"};
}