NSObject+UserModel.m
2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//
// NSObject+UserModel.m
// CNLiveUserSystemDemo
//
// Created by iOS on 16/9/18.
// Copyright © 2016年 zhulin. All rights reserved.
//
#import "NSObject+UserModel.h"
#import <objc/runtime.h>
//static const char *key = "propertiesKey";
@implementation NSObject (UserModel)
+(instancetype)modelWithKeyValues:(NSDictionary *)dict
{
id model = [[self alloc]init];
#pragma mark - 遍历properties
unsigned int count ;
objc_property_t *properties = class_copyPropertyList([self class], &count);
for ( int i = 0; i < count; i++) {
objc_property_t property = properties[i];
// 获取type
NSString *type = [NSString stringWithUTF8String:property_getAttributes(property)];
// 获取key
NSString *key = [NSString stringWithUTF8String:property_getName(property)];
// 通过key 从字典中取值
id value = dict[key];
// 判断值得类型 ,不是字典类型 ,是对象类型 : T@"NSDictionary" : 现在要获取他的对象类型,不是字典,是模型。擦
#pragma mark - 嵌套的对象--> 获取对象类名, 字典转模型
if (![type containsString:@"NS"] && [value isKindOfClass:[NSDictionary class]]) {
NSRange range = [type rangeOfString:@"@\""]; // 转义
// NSDictionary"
type = [type substringFromIndex:range.location + range.length];
range = [type rangeOfString:@"\""]; // 后面的的双引号
NSString *modelstring = [type substringToIndex:range.location];
// 获取class
Class modelClass = NSClassFromString(modelstring);
if (modelClass) { // 如果有值
value = [modelClass modelWithKeyValues:value];
}
}
#pragma mark - 数组中得字典,也要转换成对象模型
if ([value isKindOfClass:[NSArray class]]) {
if ([self respondsToSelector:@selector(arrayContainModelClass)]) { // 实现了这个协议
id idSelf = self;
NSString *type = [idSelf arrayContainModelClass][key];
Class modelClass = NSClassFromString(type);
NSMutableArray *tempArray = [NSMutableArray array];
// 遍历这个数组
for (NSDictionary *dict in value) {
id arrayModel = [modelClass modelWithKeyValues:dict];
[tempArray addObject:arrayModel];
}
value = tempArray; // 里面装的都是对象
}
}
if (value) { // 有值我才赋值,没值就忽略
[model setValue:value forKey:key];
}
}
free(properties); // 释放
return model;
}
@end