CNLiveBaseModel.m
3.35 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//
// CNLiveBaseModel.m
// CNLiveScioLive
//
// Created by CNLive-zxw on 2018/9/17.
// Copyright © 2018年 CNLive. All rights reserved.
//
#import "CNLiveBaseModel.h"
@implementation CNLiveBaseModel
- (NSDictionary *)toDictionary{
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
unsigned int count;
objc_property_t *propertyList = class_copyPropertyList([self class], &count);
for (int i = 0; i < count; i++) {
objc_property_t property = propertyList[i];
const char *cName = property_getName(property);
NSString *name = [NSString stringWithUTF8String:cName];
NSObject *value = [self valueForKey:name];//valueForKey返回的数字和字符串都是对象
if ([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSNumber class]]) {
//string , bool, int ,NSinteger
[dic setObject:value forKey:name];
} else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
//字典或字典
[dic setObject:[self arrayOrDicWithObject:(NSArray*)value] forKey:name];
} else if (value == nil) {
//null
//[dic setObject:[NSNull null] forKey:name];//这行可以注释掉?????
} else {
//model
[dic setObject:[self toDictionary] forKey:name];
}
}
return [dic copy];
}
//将可能存在model数组转化为普通数组
- (id)arrayOrDicWithObject:(id)origin {
if ([origin isKindOfClass:[NSArray class]]) {
//数组
NSMutableArray *array = [NSMutableArray array];
for (NSObject *object in origin) {
if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]]) {
//string , bool, int ,NSinteger
[array addObject:object];
} else if ([object isKindOfClass:[NSArray class]] || [object isKindOfClass:[NSDictionary class]]) {
//数组或字典
[array addObject:[self arrayOrDicWithObject:(NSArray *)object]];
} else {
//model
[array addObject:[self toDictionary]];
}
}
return [array copy];
} else if ([origin isKindOfClass:[NSDictionary class]]) {
//字典
NSDictionary *originDic = (NSDictionary *)origin;
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
for (NSString *key in originDic.allKeys) {
id object = [originDic objectForKey:key];
if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]]) {
//string , bool, int ,NSinteger
[dic setObject:object forKey:key];
} else if ([object isKindOfClass:[NSArray class]] || [object isKindOfClass:[NSDictionary class]]) {
//数组或字典
[dic setObject:[self arrayOrDicWithObject:object] forKey:key];
} else {
//model
[dic setObject:[self toDictionary] forKey:key];
}
}
return [dic copy];
}
return [NSNull null];
}
@end