iOS自学之路

字典转模型详解

2015-06-20  本文已影响1575人  木_木27

第一级别

加载plist文件,直接面对字典开发

//加载plist文件
NSString *file = [[NSBundle mainBundle] pathForResource:@"shops.plist" ofType:nil];
//这是个装着字典的数组
NSArray *dictArray = [NSArray arrayWithContentsOfFile:file];
//搞个属性来保存字典数组
@property (strong, nonatomic) NSArray *shops;
//赋值
self.shops = dictArray;
//根据字典数据来设置控件的数据
NSDictionary *data = self.shops[index];
pic.image = [UIImage imageNamed:data[@"icon"]];//pic为UIImageView
word.text = data[@"name"];//word为UILabel

第二级别

加载plist文件,直接面对模型

/**图片*/
@property (strong, nonatomic) NSString *icon;
/**名字*/
@property (strong, nonatomic) NSString *name;
//创建数组
self.shops = [NSMutableArray array];
//加载plist文件
NSString *file = [[NSBundle mainBundle] pathForResource:@"shops.plist" ofType:nil];
NSArray *dictArray = [NSArray arrayWithContentsOfFile:file];
/**************  字典转模型  **************/
for (NSDictionary *dict in dictArray) {//遍历字典数组
//创建模型对象
XMGShop *shop = [[XMGShop alloc] init];
//字典转模型
    shop.icon = dict[@"icon"];
    shop.name = dict[@"name"];
    //将模型存放到数组当中
    [self.shops addObject:shop];
}

//根据模型数据来设置控件的数据

//将模型数组里面的模型对象取出来
XMGShop *shop = self.shops[index];
pic.image = [UIImage imageNamed:shop.icon];//pic为UIImageView
word.text = shop.name;//word为UILabel

第二级别(封装)

//创建数组
self.shops = [NSMutableArray array];

//加载plist文件
NSString *file = [[NSBundle mainBundle] pathForResource:@"shops.plist" ofType:nil];
NSArray *dictArray = [NSArray arrayWithContentsOfFile:file];
/**************  字典转模型  **************/
for (NSDictionary *dict in dictArray) {//遍历字典数组
    //创建模型对象并转为模型
//            XMGShop *shop = [[XMGShop alloc] initWithDict:dict];
    XMGShop *shop = [XMGShop shopWithDict:dict];
    //将模型存放到数组当中
    [self.shops addObject:shop];
}
-(instancetype)initWithDict:(NSDictionary *)dict
{
    if (self = [super init]) {//一定要调回父类的方法
        //字典转模型
        self.icon = dict[@"icon"];
        self.name = dict[@"name"];
    }
    return self;
}
+(instancetype)shopWithDict:(NSDictionary *)dict
{
    return [[self alloc] initWithDict:dict];//这里一定要用self
}

图解

字典转模型
上一篇下一篇

猜你喜欢

热点阅读