字典转模型

/** 将image懒加载,获取图片 使用self.icon给image赋值*/
-(UIImage *)image {
    if (_image == nil) {
        _image = [UIImage imageNamed:self.icon];
    }
    return _image;
}

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

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

+ (NSArray *)appList {
    // 用数组接收plist文件的数据,通过[NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource: ofType:]]方法
    NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"app.plist" ofType:nil]];
    NSMutableArray *arrayM = [NSMutableArray array];
    for (NSDictionary *dict in array) {
        [arrayM addObject:[AppInfo appInfoWithDict:dict]];
    }
    return  arrayM;
}

 字典转模型,模型负责所有该模型所具备的属性的实现

1> 创建模型类AppInfo,并且增加相对应的字典键值属性
2> initWithDict对象方法
3> appInfoWithDict类方法
4> 函数返回值instancetype
* 只能用于返回类型
* 可以辅助类方法做类型推断,在开发时减少错误
5> 将模型获取数据的方法AppList也放在模型类中实现
6> KVC的使用获取字典值,简化代码
7> 增加image属性,将不属于plist中的数据但是属于XIB文件中的需要的数据也放在模型中
8> 只读属性和@synthesize合成指令

原文地址:https://www.cnblogs.com/LiuLady12138/p/4605512.html