创建一个通用头文件宏
#ifndef _7__________NJGlobal_h
#define _7__________NJGlobal_h
#define NJInitH(name) \
- (instancetype)initWithDict:(NSDictionary *)dict; \
+ (instancetype)name##WithDict:(NSDictionary *)dict;
#define NJInitM(name)\
- (instancetype)initWithDict:(NSDictionary *)dict \
{ \
if (self = [super init]) { \
[self setValuesForKeysWithDictionary:dict]; \
} \
return self; \
} \
+ (instancetype)name##WithDict:(NSDictionary *)dict \
{ \
return [[self alloc] initWithDict:dict]; \
}
#endif
初始化数据
#import "NJGroup.h"
#import "NJCar.h"
#import "NJGlobal.h"
@implementation NJGroup
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init]) {
// 赋值属性
// [self setValuesForKeysWithDictionary:dict];
self.title = dict[@"title"];
NSArray *dictArray = dict[@"cars"];
// 将字典转换为模型
NSMutableArray *models = [NSMutableArray arrayWithCapacity:dictArray.count];
for (NSDictionary *dict in dictArray) {
NJCar *car = [NJCar carWithDict:dict];
[models addObject:car];
}
// 赋值存储模型的数组给属性
self.cars = models;
}
return self;
}
+ (instancetype)groupWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
@end