[iOS基础控件 - 4.2] APP列表 字典转模型Model

时间:2021-06-24 14:29:39
A.使用字典加载数据的缺点
1.用户自行指定key,容易出错
2.存入、取出都需要key,容易混乱
 
B.模型 (MVC中的model)
1.字典与模型对比:
(1)字典:存储数据,通过字符串类型的key取值(容易写错,写错了key编译器不会报错)
(2)模型:存储数据,自定义属性存储数据,其实就类似JavaBean,本质是数据封装
 
2.实现
(1)定义模型类
 @interface App : NSObject

 /**
copy : NSString
strong: 一般对象
weak: UI控件
assign: 基本数据类型
*/ /**
名称
*/
@property(nonatomic, copy) NSString *name; /**
图标
*/
@property(nonatomic, copy) NSString *icon;
@end
 
(2)使用模型读取存储、读取数据
存储:
 #pragma mark 取得应用列表
- (NSArray *) apps {
if (nil == _apps) {
// 1.获得plist的全路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"app.plist" ofType:nil]; // 2.加载数据
NSArray *dictArray = [NSArray arrayWithContentsOfFile:path]; // 3.将dictArray里面的所有字典转成模型,放到新数组中
NSMutableArray *appArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
// 3.1创建模型对象
App *app = [[App alloc] init]; // 3.2 将字典的所有属性赋值给模型
app.name = dict[NAME_KEY];
app.icon = dict[ICON_KEY]; // 3.3 添加到app数组中
[appArray addObject:app];
} _apps = appArray;
} return _apps;
}
 
读取:
         iconView.image = [UIImage imageNamed:appData.icon];
[appView addSubview:iconView]; // 2.设置APP名字
UILabel *nameLabel = [[UILabel alloc] init];
nameLabel.text = appData.name;
 
C.Model改进
     在ViewControl中解析、存储数据, 增加了数据、类的耦合性,控制器关心太多,在Model被修改之后难以进行自我修改.
     解决 : ==> 所以在Model中解析数据
1.实现
(1)自定义带数据参数的构造方法
声明:
 /**
自定义构造方法
通过字典来初始化模型对象
*/
- (id) initWithDictionary:(NSDictionary *) dictionary;
 
实现:
 - (id) initWithDictionary:(NSDictionary *) dictionary {
if (self = [super init]) {
self.name = dictionary[NAME_KEY];
self.icon = dictionary[ICON_KEY];
} return self;
}
 
使用:
             // 3.1创建模型对象
App *app = [[App alloc] initWithDictionary:dict]; // 3.2 添加到app数组中
[appArray addObject:app];
 
(2)进一步提供类方法
 + (id) appWithDictionary:(NSDictionary *) dictionary {
// 使用self代表类名代替真实类名,防止子类调用出错
return [[self alloc] initWithDictionary:dictionary];
}
 
D.使用”instancetype”代替”id"
id: 代指所有类型,但是使用不恰当的类型指针指向不匹配的对象时,编译器不会报错、警告,但在运行时很可能会出错
[iOS基础控件 - 4.2] APP列表 字典转模型Model
 
instantcetype:
1.能指向任何类型
2.编译器能够根据当前指向的对象,自动检查变量类型是否正确,进而发出警告
3.只能作为返回值,不能用作参数

[iOS基础控件 - 4.2] APP列表 字典转模型Model