在IOS开发中,要做字典转模型一般情况如下:
1 /** 2 * 声明方法 3 */ 4 - (instancetype) initWithDictionary:(NSDictionary *)dict; 5 + (instancetype) carWithDictionary:(NSDictionary *)dict; 6 7 /** 8 * 实现方法 9 */ 10 - (instancetype)initWithDictionary:(NSDictionary *)dict 11 { 12 if (self = [super init]) { 13 [self setValuesForKeysWithDictionary:dict]; 14 } 15 return self; 16 } 17 18 + (instancetype)carWithDictionary:(NSDictionary *)dict 19 { 20 return [[ZYCar alloc]initWithDictionary:dict]; 21 }
先在头文件中声明,再在.m
文件中实现具体的方法,而且这些方法的内容基本一致,可以用宏简化。
2.新建一个.h文件,并在其中添加如下代码:
1 #define InitH(name) 2 - (instancetype)initWithDict:(NSDictionary *)dict; 3 + (instancetype)name##WithDict:(NSDictionary *)dict; 4 5 #define InitM(name) 6 - (instancetype)initWithDict:(NSDictionary *)dict 7 { 8 if (self = [super init]) { 9 [self setValuesForKeysWithDictionary:dict]; 10 } 11 return self; 12 } 13 + (instancetype)name##WithDict:(NSDictionary *)dict 14 { 15 return [[self alloc] initWithDict:dict]; 16 } 17 18 #endif
引用这个.h文件后,上面方法的声明和实现可以化简为一句
InitH(name);InitM(name); name为模型类名