iOS开发iOS学习

iOS 字典转模型

2016-11-27  本文已影响0人  azhang_coder

字典转模型



-(instancetype)initWithDict:(NSDictionary *)dict

{

 if (self=[super init]) {

 self.name=dict[@"name"];

 self.icon=dict[@"icon"];

 //简单的字典转模型可以直接采用KVC来转

// [self setValuesForKeysWithDictionary:dict];

 }

 return self;

}

+(instancetype)carsWithDict:(NSDictionary *)dict

{

 return [[self alloc]initWithDict:dict];

}


/*分组 */

@interface AZCarGroup : NSObject

/*车模型数组 */

@property(nonatomic,strong)NSArray *cars;

/*组名*/

@property(nonatomic,copy)NSString *title;

-(instancetype)initWithDict:(NSDictionary *)dict;

+(instancetype)carGroupWithDict:(NSDictionary *)dict;


-(instancetype)initWithDict:(NSDictionary *)dicts

{

 if (self=[super init]) {

 self.title=dicts[@"title"];

 //将字典数组中的字典转为车模型存放到头文件的数组中

 NSMutableArray *cars=[NSMutableArray array];

 for (NSDictionary *dict in dicts[@"cars"]) {

 AZCar *car=[AZCar carsWithDict:dict];

 [cars addObject:car];

 }

 self.cars=cars;

 }

 return self;

}

+(instancetype)carGroupWithDict:(NSDictionary *)dicts

{

 return [[self alloc]initWithDict:dicts];

}


//所有车数据

-(NSArray *)carGroups

{

 if (_carGroups==nil) {

 //加载plist数据

 NSArray *dictArr=[NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"cars.plist" ofType:nil]];

 //字典转模型

 NSMutableArray *tempArray=[NSMutableArray array];

 for (NSDictionary *dict in dictArr) {

 AZCarGroup *carGroup=[AZCarGroup carGroupWithDict:dict];

 [tempArray addObject:carGroup];

 }

 self.carGroups=tempArray;

 }

 return _carGroups;

}

#import "MJExtension.h"


 //所有车数据 

-(NSArray *)carGroups

{

 if (_carGroups==nil) {

 //通过返回的字典确定cars数组中所装的内容为AZCar模型

 [AZCarGroup mj_setupObjectClassInArray:^NSDictionary *{

    return @{@"cars":[AZCar class]};

 }];

 _carGroups=[AZCarGroup mj_objectArrayWithFilename:@"cars.plist"];

 }

 return _carGroups;

}

    /**
    [item setValue:@"中国" forKeyPath:@"name"];
     setValue:forKeyPath实现原理
     1.先查看有没有对应key值的set方法,如果有set方法,就会调用set方法,给对应的属性赋值
     2.如果没有set方法,去查看有没有跟key值相同并且带有下划线的成员属性.如果有的话,就给带有下划线的成员属性赋值
     3.如果没有跟key值相同并且带有下划线的成员属性,还会去找有没有跟key值相同名称的成员属性.如果有,就给它赋值.
     4.如果没有直接报错.
     */```

//setValuesForKeysWithDictionary实现原理
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
[item setValue:obj forKeyPath:key];
NSLog(@"%@--%@",key,obj);
}];

return item;

}

// 可以在set方法赋值前修改该属性类型(运行时)
-(void)setIcon:(UIImage *)icon{

NSString *imageName = (NSString *)icon;
_icon =  [UIImage imageNamed:imageName];

}

-(void)setIcon:(NSString *)icon{

// NSString *imageName = (NSString *)icon;

_icon =  [UIImage imageNamed:icon];

}



上一篇下一篇

猜你喜欢

热点阅读