iOS開發UI篇—字典轉模型

iOS開發UI篇—字典轉模型數組

1、能完成功能的「問題代碼」app

1.從plist中加載的數據編輯器

2.實現的代碼ide

複製代碼

//
// LFViewController.m
// 03-應用管理
//
// Created by apple on 14-5-22.
// Copyright (c) 2014年 heima. All rights reserved.
//優化

#import "LFViewController.h"動畫

@interface LFViewController ()
@property (nonatomic, strong) NSArray *appList;
@end編碼

@implementation LFViewControlleratom

- (NSArray *)appList
{
if (!_appList) {spa

// 1. 從mainBundle加載
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"app.plist" ofType:nil];
_appList = [NSArray arrayWithContentsOfFile:path];

NSLog(@"%@", _appList);
}
return _appList;
}指針

- (void)viewDidLoad
{
[super viewDidLoad];

// 總共有3列
int totalCol = 3;
CGFloat viewW = 80;
CGFloat viewH = 90;

CGFloat marginX = (self.view.bounds.size.width - totalCol * viewW) / (totalCol + 1);
CGFloat marginY = 10;
CGFloat startY = 20;

for (int i = 0; i < self.appList.count; i++) {

int row = i / totalCol;
int col = i % totalCol;

CGFloat x = marginX + (viewW + marginX) * col;
CGFloat y = startY + marginY + (viewH + marginY) * row;

UIView *appView = [[UIView alloc] initWithFrame:CGRectMake(x, y, viewW, viewH)];

[self.view addSubview:appView];

// 建立appView內部的細節
// 0> 讀取數組中的字典
NSDictionary *dict = self.appList[i];

// 1> UIImageView
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, viewW, 50)];
imageView.image = [UIImage imageNamed:dict[@"icon"]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[appView addSubview:imageView];

// 2> UILabel
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.bounds.size.height, viewW, 20)];
// 設置文字
label.text = dict[@"name"];
label.font = [UIFont systemFontOfSize:12.0];
label.textAlignment = NSTextAlignmentCenter;

[appView addSubview:label];

// 3> UIButton
// UIButtonTypeCustom和[[UIButton alloc] init]是等價的
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(15, 70, viewW - 30, 20);

[button setTitle:@"下載" forState:UIControlStateNormal];
// *** 不能使用以下代碼直接設置title
// button.titleLabel.text = @"下載";
// @property中readonly表示不容許修改對象的指針地址,可是能夠修改對象的屬性
button.titleLabel.font= [UIFont systemFontOfSize:14.0];

[button setBackgroundImage:[UIImage imageNamed:@"buttongreen"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"] forState:UIControlStateHighlighted];

[appView addSubview:button];
}
}

@end

 
 
複製代碼

3.實現效果

4.代碼問題

在上述代碼的第62,69行,咱們是直接經過字典的鍵名獲取plist中的數據信息,在viewController中須要直接和數據打交道,若是須要屢次使用可能會由於不當心把鍵名寫錯,而程序並不報錯。鑑於此,能夠考慮把字典數據轉換成一個模型,把數據封裝到一個模型中去,讓viewController再也不直接和數據打交道,而是和模型交互。

通常狀況下,設置數據和取出數據都使用「字符串類型的key」,編寫這些key時,編輯器沒有智能提示,須要手敲。如:

dict[@"name"] = @"Jack";

NSString *name = dict[@"name"];

手敲字符串key,key容易寫錯

Key若是寫錯了,編譯器不會有任何警告和報錯,形成設錯數據或者取錯數據

2、字典轉模型

1.字典轉模型介紹

示意圖:

 

字典轉模型的好處:

(1)下降代碼的耦合度

(2)全部字典轉模型部分的代碼統一集中在一到處理,下降代碼出錯的概率

(3)在程序中直接使用模型的屬性操做,提升編碼效率 

(4)調用方不用關心模型內部的任何處理細節

字典轉模型的注意點:

模型應該提供一個能夠傳入字典參數的構造方法

- (instancetype)initWithDict:(NSDictionary *)dict;

+ (instancetype)xxxWithDict:(NSDictionary *)dict;

提示:在模型中合理地使用只讀屬性,能夠進一步下降代碼的耦合度。

 

 2.代碼示例(一)

新建一個類,用來做爲數據模型

viewController.m文件代碼(字典轉模型)

#import "LFViewController.h"
#import "LFAppInfo.h"

@interface LFViewController ()
@property (nonatomic, strong) NSArray *appList;
@end

@implementation LFViewController

// 字典轉模型
- (NSArray *)appList
{
if (!_appList) {
// 1. 從mainBundle加載
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"app.plist" ofType:nil];
// _appList = [NSArray arrayWithContentsOfFile:path];

NSArray *array = [NSArray arrayWithContentsOfFile:path];
// 將數組轉換成模型,意味着self.appList中存儲的是LFAppInfo對象
// 1. 遍歷數組,將數組中的字典依次轉換成AppInfo對象,添加到一個臨時數組
// 2. self.appList = 臨時數組

NSMutableArray *arrayM = [NSMutableArray array];
for (NSDictionary *dict in array) {
//用字典來實例化對象的工廠方法
[arrayM addObject:[LFAppInfo appInfoWithDict:dict]];
}

_appList = arrayM;
}
return _appList;
}

- (void)viewDidLoad
{
[super viewDidLoad];

// 總共有3列
int totalCol = 3;
CGFloat viewW = 80;
CGFloat viewH = 90;

CGFloat marginX = (self.view.bounds.size.width - totalCol * viewW) / (totalCol + 1);
CGFloat marginY = 10;
CGFloat startY = 20;

for (int i = 0; i < self.appList.count; i++) {

int row = i / totalCol;
int col = i % totalCol;

CGFloat x = marginX + (viewW + marginX) * col;
CGFloat y = startY + marginY + (viewH + marginY) * row;

UIView *appView = [[UIView alloc] initWithFrame:CGRectMake(x, y, viewW, viewH)];

[self.view addSubview:appView];

// 建立appView內部的細節
// 0> 讀取數組中的AppInfo
// NSDictionary *dict = self.appList[i];
LFAppInfo *appInfo = self.appList[i];

// 1> UIImageView
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, viewW, 50)];
imageView.image = appInfo.image;
imageView.contentMode = UIViewContentModeScaleAspectFit;

[appView addSubview:imageView];

// 2> UILabel
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.bounds.size.height, viewW, 20)];
// 設置文字
label.text = appInfo.name;
label.font = [UIFont systemFontOfSize:12.0];
label.textAlignment = NSTextAlignmentCenter;

[appView addSubview:label];

// 3> UIButton
// UIButtonTypeCustom和[[UIButton alloc] init]是等價的
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(15, 70, viewW - 30, 20);

[button setTitle:@"下載" forState:UIControlStateNormal];
button.titleLabel.font= [UIFont systemFontOfSize:14.0];

[button setBackgroundImage:[UIImage imageNamed:@"buttongreen"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"] forState:UIControlStateHighlighted];

[appView addSubview:button];
button.tag = i;

[button addTarget:self action:@selector(downloadClick:) forControlEvents:UIControlEventTouchUpInside];
}
}

- (void)downloadClick:(UIButton *)button
{
NSLog(@"%d", button.tag);
// 實例化一個UILabel顯示在視圖上,提示用戶下載完成
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(80, 400, 160, 40)];
label.textAlignment = NSTextAlignmentCenter;
label.backgroundColor = [UIColor lightGrayColor];

LFAppInfo *appInfo = self.appList[button.tag];
label.text = [NSString stringWithFormat:@"下載%@完成", appInfo.name];
label.font = [UIFont systemFontOfSize:13.0];
label.alpha = 1.0;
[self.view addSubview:label];

// 動畫效果
// 動畫效果完成以後,將Label從視圖中刪除
// 首尾式動畫,只能作動畫,要處理完成後的操做不方便
// [UIView beginAnimations:nil context:nil];
// [UIView setAnimationDuration:1.0];
// label.alpha = 1.0;
// [UIView commitAnimations];

// block動畫比首尾式動畫簡單,並且可以控制動畫結束後的操做
// 在iOS中,基本都使用首尾式動畫
[UIView animateWithDuration:2.0 animations:^{
label.alpha = 0.0;
} completion:^(BOOL finished) {
// 刪除label
[label removeFromSuperview];
}];
}

@end

 
 
複製代碼

模型.h文件代碼

複製代碼

#import <Foundation/Foundation.h>

@interface LFAppInfo : NSObject

// 應用程序名稱
@property (nonatomic, copy) NSString *name;
// 應用程序圖標名稱
@property (nonatomic, copy) NSString *icon;

// 圖像
// 定義屬性時,會生成getter&setter方法,還會生成一個帶下劃線的成員變量
// 若是是readonly屬性,只會生成getter方法,同時沒有成員變量
@property (nonatomic, strong, readonly) UIImage *image;

// instancetype會讓編譯器檢查實例化對象的準確類型
// instancetype只能用於返回類型,不能當作參數使用

- (instancetype)initWithDict:(NSDictionary *)dict;
/** 工廠方法 */
+ (instancetype)appInfoWithDict:(NSDictionary *)dict;

@end

 
 
複製代碼

模型.m文件數據處理代碼

複製代碼

#import "LFAppInfo.h"

@interface LFAppInfo()
{
UIImage *_imageABC;
}
@end

@implementation LFAppInfo

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

+ (instancetype)appInfoWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}

- (UIImage *)image
{
if (!_imageABC) {
_imageABC = [UIImage imageNamed:self.icon];
}
return _imageABC;
}

@end

 
 
複製代碼

3.代碼示例(二)

數據信息:plist文件

字典轉模型(初步)

模型.h文件

複製代碼

#import <Foundation/Foundation.h>

@interface LFQuestion : NSObject

@property (nonatomic, copy) NSString *answer;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, strong) NSArray *options;

@property (nonatomic, strong) UIImage *image;

/** 用字典實例化對象的成員方法 */
- (instancetype)initWithDict:(NSDictionary *)dict;
/** 用字典實例化對象的類方法,又稱工廠方法 */
+ (instancetype)questionWithDict:(NSDictionary *)dict;
@end

 
 
複製代碼

模型.m文件

複製代碼

#import "LFQuestion.h"

@implementation LFQuestion

+ (instancetype)questionWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}

- (instancetype)initWithDict:(NSDictionary *)dict
{
self = [super init];
if (self) {
self.answer = dict[@"answer"];
self.icon = dict[@"icon"];
self.title = dict[@"title"];
self.options = dict[@"options"];

[self setValuesForKeysWithDictionary:dict];
}
return self;
}

複製代碼

viewController.m文件中的數據處理

複製代碼

- (NSArray *)questions
{
if (!_questions) {

NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"questions.plist" ofType:nil]];

NSMutableArray *arrayM = [NSMutableArray array];

for (NSDictionary *dict in array) {
[arrayM addObject:[LFQuestion questionWithDict:dict]];
}
_questions=arrayM;
}
return _questions;
}

複製代碼

字典轉模型(優化)

上面代碼能夠作進一步的優化,從plist文件中讀取數據是能夠交給模型去處理的,優化後代碼以下:

模型.h文件

複製代碼

#import <Foundation/Foundation.h>

@interface LFQuestion : NSObject

@property (nonatomic, copy) NSString *answer;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, strong) NSArray *options;

@property (nonatomic, strong) UIImage *image;

/** 用字典實例化對象的成員方法 */
- (instancetype)initWithDict:(NSDictionary *)dict;
/** 用字典實例化對象的類方法,又稱工廠方法 */
+ (instancetype)questionWithDict:(NSDictionary *)dict;

/** 從plist加載對象數組 */
+ (NSArray *)questions;

@end

 
 
複製代碼

模型.m文件

複製代碼

#import "LFQuestion.h"

@implementation LFQuestion

+ (instancetype)questionWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}

- (instancetype)initWithDict:(NSDictionary *)dict
{
self = [super init];
if (self) {
self.answer = dict[@"answer"];
self.icon = dict[@"icon"];
self.title = dict[@"title"];
self.options = dict[@"options"];

[self setValuesForKeysWithDictionary:dict];
}
return self;
}


+ (NSArray *)questions
{
NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"questions.plist" ofType:nil]];

NSMutableArray *arrayM = [NSMutableArray array];

for (NSDictionary *dict in array) {
[arrayM addObject:[LFQuestion questionWithDict:dict]];
}

return arrayM;
}
@end

 
 
複製代碼

viewController.m文件中的數據處理代碼部分

複製代碼

- (NSArray *)questions
{
if (!_questions) {
_questions = [LFQuestion questions];
}
return _questions;
}

 
 
複製代碼

補充內容:(KVC)的使用

(1)在模型內部的數據處理部分,能夠使用鍵值編碼來進行處理

複製代碼

- (instancetype)initWithDict:(NSDictionary *)dict
{
self = [super init];
if (self) {
// self.answer = dict[@"answer"];
// self.icon = dict[@"icon"];
// self.title = dict[@"title"];
// self.options = dict[@"options"];

// KVC (key value coding)鍵值編碼
// cocoa 的大招,容許間接修改對象的屬性值
// 第一個參數是字典的數值
// 第二個參數是類的屬性
[self setValue:dict[@"answer"] forKeyPath:@"answer"];
[self setValue:dict[@"icon"] forKeyPath:@"icon"];
[self setValue:dict[@"title"] forKeyPath:@"title"];
[self setValue:dict[@"options"] forKeyPath:@"options"];
}
return self;
}

複製代碼

(2)setValuesForKeys的使用

上述數據操做細節,能夠直接經過setValuesForKeys方法來完成。

複製代碼

- (instancetype)initWithDict:(NSDictionary *)dict
{
self = [super init];
if (self) {
// 使用setValuesForKeys要求類的屬性必須在字典中存在,能夠比字典中的鍵值多,可是不能少。
[self setValuesForKeysWithDictionary:dict];
}
return self;
}

複製代碼

3、補充說明

1.readonly屬性

 (1)@property中readonly表示不容許修改對象的指針地址,可是能夠修改對象的屬性。

 (2)一般使用@property關鍵字定義屬性時,會生成getter&setter方法,還會生成一個帶下劃線的成員變量。

 (3)若是是readonly屬性,只會生成getter方法,不會生成帶下劃線的成員變量.

2.instancetype類型

(1)instancetype會讓編譯器檢查實例化對象的準確類型 
(2)instancetype只能用於返回類型,不能當作參數使用

3.instancetype & id的比較

(1) instancetype在類型表示上,跟id同樣,能夠表示任何對象類型

(2) instancetype只能用在返回值類型上,不能像id同樣用在參數類型上

(3) instancetype比id多一個好處:編譯器會檢測instancetype的真實類型

相關文章
相關標籤/搜索