第一級別
加載plist文件,直接面對字典
開發(fā)
-
設置plist文件(死數(shù)據(jù)):
加載plist以及面對字典開發(fā):
//加載plist文件
NSString *file = [[NSBundle mainBundle] pathForResource:@"shops.plist" ofType:nil];
//這是個裝著字典的數(shù)組
NSArray *dictArray = [NSArray arrayWithContentsOfFile:file];
//搞個屬性來保存字典數(shù)組
@property (strong, nonatomic) NSArray *shops;
//賦值
self.shops = dictArray;
//根據(jù)字典數(shù)據(jù)來設置控件的數(shù)據(jù)
NSDictionary *data = self.shops[index];
pic.image = [UIImage imageNamed:data[@"icon"]];//pic為UIImageView
word.text = data[@"name"];//word為UILabel
第二級別
加載plist文件,直接面對模型
發(fā)
- 加載plist文件厘贼;
-
新建模型類,創(chuàng)建模型對象:
- 如果plist文件里面字典有幾個key,模型類就應該聲明幾個屬性
/**圖片*/
@property (strong, nonatomic) NSString *icon;
/**名字*/
@property (strong, nonatomic) NSString *name;
- 在控制器文件里面進行字典轉(zhuǎn)模型
//創(chuàng)建數(shù)組
self.shops = [NSMutableArray array];
//加載plist文件
NSString *file = [[NSBundle mainBundle] pathForResource:@"shops.plist" ofType:nil];
NSArray *dictArray = [NSArray arrayWithContentsOfFile:file];
/************** 字典轉(zhuǎn)模型 **************/
for (NSDictionary *dict in dictArray) {//遍歷字典數(shù)組
//創(chuàng)建模型對象
XMGShop *shop = [[XMGShop alloc] init];
//字典轉(zhuǎn)模型
shop.icon = dict[@"icon"];
shop.name = dict[@"name"];
//將模型存放到數(shù)組當中
[self.shops addObject:shop];
}
//根據(jù)模型數(shù)據(jù)來設置控件的數(shù)據(jù)
//將模型數(shù)組里面的模型對象取出來
XMGShop *shop = self.shops[index];
pic.image = [UIImage imageNamed:shop.icon];//pic為UIImageView
word.text = shop.name;//word為UILabel
第二級別(封裝)
//創(chuàng)建數(shù)組
self.shops = [NSMutableArray array];
//加載plist文件
NSString *file = [[NSBundle mainBundle] pathForResource:@"shops.plist" ofType:nil];
NSArray *dictArray = [NSArray arrayWithContentsOfFile:file];
/************** 字典轉(zhuǎn)模型 **************/
for (NSDictionary *dict in dictArray) {//遍歷字典數(shù)組
//創(chuàng)建模型對象并轉(zhuǎn)為模型
// XMGShop *shop = [[XMGShop alloc] initWithDict:dict];
XMGShop *shop = [XMGShop shopWithDict:dict];
//將模型存放到數(shù)組當中
[self.shops addObject:shop];
}
- 模型類內(nèi)部封裝好的方法:
-(instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init]) {//一定要調(diào)回父類的方法
//字典轉(zhuǎn)模型
self.icon = dict[@"icon"];
self.name = dict[@"name"];
}
return self;
}
+(instancetype)shopWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];//這里一定要用self
}