1 #import "LYSBaseModel.h"
2
3 @implementation LYSBaseModel
4
5 // 自定义初始化方法
6 - (id)initWithContentDic:(NSDictionary *)dic
7 {
8 self = [super init];
9 if (self) {
10
11 // 1.获取映射关系字典
12 NSDictionary *keySetAtt = [self valueAndKeyWithContentDic:dic];
13
14 // 2.把字典里面的内容写入到对应的属性里面
15 for (NSString *key in dic) {
16 // 01 获取对应的value
17 id value = dic[key];
18 // 02 获取需要写入属性的名字
19 NSString *attName = keySetAtt[key];
20 // 03 通过set方法把值写入到属性中
21 SEL action = [self getMethodWithAttName:attName];
22 // 04判断当前对象是否有这个set方法,如果有就证明当前对象有这个属性
23 if ([self respondsToSelector:action]) {
24 // 把参数写入到属性中
25 SuppressPerformSelectorLeakWarning(
26 [self performSelector:action withObject:value]
27 );
28 }
29 }
30 }
31 return self;
32 }
33 // 通过属性的名字获取对应的set方法
34 - (SEL)getMethodWithAttName:(NSString *)attName
35 {
36 /*
37 image
38 setImage:
39 */
40 NSString *firstChar = [[attName substringToIndex:1] uppercaseString];
41 NSString *endString = [attName substringFromIndex:1];
42 NSString *methodName = [NSString stringWithFormat:@"set%@%@:",firstChar,endString];
43 return NSSelectorFromString(methodName);
44 }
45
46 // 创建映射关系
47 - (NSDictionary *)valueAndKeyWithContentDic:(NSDictionary *)dic
48 {
49 /*
50 id:123
51 image:http://asd
52 type:2
53
54 字典的key:属性的名字
55 id:id
56 image:image
57 type:type
58 */
59 NSMutableDictionary *params = [NSMutableDictionary dictionary];
60 for (NSString *key in dic) {
61 // 把字典的key添加到字典里面
62 [params setObject:key forKey:key];
63 }
64 return params;
65 }
66
67 @end