对象转模型
——————————————————————————————————————————————————————
CarGroup.h
#import <Foundation/Foundation.h>
@interface MJCarGroup : NSObject
/**
* 这组的标题
*/
@property (nonatomic, copy) NSString *title;
/**
* 存放的所有的汽车品牌(里面装的都是MJCar模型)
*/
@property (nonatomic, strong) NSArray *cars;
+ (instancetype)groupWithDict:(NSDictionary *)dict;
- (instancetype)initWithDict:(NSDictionary *)dict;
@end
——————————————————————————————————————————————————————
CarGroup.m
#import "MJCarGroup.h"
#import "MJCar.h"
@implementation MJCarGroup
+ (instancetype)groupWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init]) {
// 赋值标题
self.title = dict[@"title"];
// 取出原来的字典数组
NSArray *dictArray = dict[@"cars"];
NSMutableArray *carArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
MJCar *car = [MJCar carWithDict:dict];
[carArray addObject:car];
}
self.cars = carArray;
}
return self;
}
@end
——————————————————————————————————————————————————————
Car.h
#import <Foundation/Foundation.h>
@interface MJCar : NSObject
/**
* 图标
*/
@property (nonatomic, copy) NSString *icon;
/**
* 名称
*/
@property (nonatomic, copy) NSString *name;
+ (instancetype)carWithDict:(NSDictionary *)dict;
- (instancetype)initWithDict:(NSDictionary *)dict;
@end
——————————————————————————————————————————————————————
Car.m
@implementation MJCar
+ (instancetype)carWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
@end
——————————————————————————————————————————————————————
- (NSArray *)groups
{
if (_groups == nil) {
// 初始化
// 1.获得plist的全路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"cars_total.plist" ofType:nil];
// 2.加载数组
NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
// 3.将dictArray里面的所有字典转成模型对象,放到新的数组中
NSMutableArray *groupArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
// 3.1.创建模型对象
MJCarGroup *group = [MJCarGroup groupWithDict:dict];
// 3.2.添加模型对象到数组中
[groupArray addObject:group];
}
// 4.赋值
_groups = groupArray;
}
return _groups;
}