A.使用字典加载数据的缺点
1.用户自行指定key,容易出错
2.存入、取出都需要key,容易混乱
B.模型 (MVC中的model)
1.字典与模型对比:
(1)字典:存储数据,通过字符串类型的key取值(容易写错,写错了key编译器不会报错)
(2)模型:存储数据,自定义属性存储数据,其实就类似javaBean,本质是数据封装
2.实现
(1)定义模型类
1@interfaceApp : NSObject23/**4copy : NSString5strong: 一般对象6weak: UI控件7assign: 基本数据类型8*/910/**11名称12*/13@PRoperty(nonatomic, copy) NSString *name;1415/**16图标17*/18@property(nonatomic, copy) NSString *icon;19@end
(2)使用模型读取存储、读取数据
存储:
1#pragmamark 取得应用列表2- (NSArray *) apps {3if(nil ==_apps) {4//1.获得plist的全路径5NSString *path = [[NSBundle mainBundle] pathForResource:@"app.plist"ofType:nil];67//2.加载数据8NSArray *dictArray =[NSArray arrayWithContentsOfFile:path];910//3.将dictArray里面的所有字典转成模型,放到新数组中11NSMutableArray *appArray =[NSMutableArray array];12for(NSDictionary *dictindictArray) {13//3.1创建模型对象14App *app =[[App alloc] init];1516//3.2 将字典的所有属性赋值给模型17app.name =dict[NAME_KEY];18app.icon =dict[ICON_KEY];1920//3.3 添加到app数组中21[appArray addObject:app];22}2324_apps =appArray;25}2627return_apps;28}
读取:
1iconView.image =[UIImage imageNamed:appData.icon];2[appView addSubview:iconView];34//2.设置APP名字5UILabel *nameLabel =[[UILabel alloc] init];6nameLabel.text = appData.name;
C.Model改进
在ViewControl中解析、存储数据, 增加了数据、类的耦合性,控制器关心太多,在Model被修改之后难以进行自我修改.
解决 : ==> 所以在Model中解析数据
1.实现
(1)自定义带数据参数的构造方法
声明:
1/**2自定义构造方法3通过字典来初始化模型对象4*/5- (id) initWithDictionary:(NSDictionary *) dictionary;
实现:
1- (id) initWithDictionary:(NSDictionary *) dictionary {2if(self =[super init]) {3self.name =dictionary[NAME_KEY];4self.icon =dictionary[ICON_KEY];5}67returnself;8}
使用:
1//3.1创建模型对象2App *app =[[App alloc] initWithDictionary:dict];34//3.2 添加到app数组中5[appArray addObject:app];
(2)进一步提供类方法
1+ (id) appWithDictionary:(NSDictionary *) dictionary {2//使用self代表类名代替真实类名,防止子类调用出错3return[[self alloc] initWithDictionary:dictionary];4}
D.使用”instancetype”代替”id"
id: 代指所有类型,但是使用不恰当的类型指针指向不匹配的对象时,编译器不会报错、警告,但在运行时很可能会出错
instantcetype:
1.能指向任何类型
2.编译器能够根据当前指向的对象,自动检查变量类型是否正确,进而发出警告
3.只能作为返回值,不能用作参数