数据模型

字典取数据的缺点,key写错了不好调试。

data model 一般继承NSObject

假设字典为icon 和 name

@interface Shop: NSObject
@property(nonatomic, copy)NSString*name;
@property(nonatomic, copy)NSString*icon;
@end

@implement XXX
NSDictionary* dict = self.shops[index];//获取一条字典数据
Shop *shop = [[Shop alloc] init];
shop.name = dict[@"name"];
shop.icon = dict[@"icon"];
@end

update1 如果新增一条属性,则上面也都需要修改

@interface Shop: NSObject
@property(nonatomic, copy)NSString*name;
@property(nonatomic, copy)NSString*icon;
- (id) initWithDict:(NSDictionary*) dict;
@end

@implement Shop
- (id) initWithDict:(NSDictionary*) dict {
    if (self = [super init]) {
        self.name = dict[@"name"];
        self.icon = dict[@"icon"];
    }
    return self;
}
@end

@implement XXX
NSDictionary* dict = self.shops[index];//获取一条字典数据
Shop *shop = [[Shop alloc]initWithDict:dict];
//不需要再设置了shop.name = dict[@"name"];了
@end

update2通过创建类方法直接简化

/*
类方法已shop开头
[Shop shopWith];
[NSString stringWithXX];
[NSDta dataWithxxx];
*/

(id) shopWithDict:(NSDictionary*) dict {
    return [[self alloc] initWithDict:dict];
}

使用:

Shop *shop = [Shop initWithDict:dict];

update3 直接在用property shops 存放数据模型 将所有id改为instancetype

1.最终目标, 将字典数组转为模型数组shops。

Shop *shop = self.shops[index];

直接使用:shop.icon, shop.name;

2.数据模型: BLShop.h, BLShop.m

//BLShop.h
@interface BLShop:NSObject
@property (nonatomic, copy)NSString* icon;
@property (nonatomic, copy)NSString* name;
+ (instancetype) initWithDict:(NSDictionary*)dict;
+ (instancetype) shopWithDict:(NSDictionary*)dict;
@end

//BLShop.m
@implementation BLShop
+ (instancetype) initWithDict:(NSDictionary*)dict {
    if (self = [super init]) {
        self.icon = dict[@"icon"];
        self.name = dict[@"name"];
    }
    return self;
}
@end

3.使用数据模型的类

@property(nonatomic, strong)NSMutableArray* shops;
(NSArray*) shops {
    if (_shop == nil) {
        //获取dictionary 数组
        NSString *file = [[NSBundle main] pathForResrouce:..@"plist"];
        NSArray* dictArr = [NSArray arrayWithContentFile:file];
        NSMutableArray *shopsArray = [NSMutableArray array];
        for (NSDictionary *dict in dictArr) {
            Shop *shop = [Shop shopWithDict:dict];
            [shopsArray addObject:shop];
        }
        _shops = shopsArray;
    }
    return _shops;
}

4.使用:数据取出的就是模型了

Shop *shop = self.shops[index];

总体思路:字典数组转为模型数组

results matching ""

    No results matching ""