iOS開發UI篇—字典轉模型

來源:互聯網
上載者:User

標籤:

iOS開發UI篇—字典轉模型

一、能完成功能的“問題代碼”

1.從plist中載入的資料

2.實現的代碼

 1 // 2 //  LFViewController.m 3 //  03-應用管理 4 // 5 //  Created by apple on 14-5-22. 6 //  Copyright (c) 2014年 heima. All rights reserved. 7 // 8  9 #import "LFViewController.h"10 11 @interface LFViewController ()12 @property (nonatomic, strong) NSArray *appList;13 @end14 15 @implementation LFViewController16 17 - (NSArray *)appList18 {19     if (!_appList) {20 21         // 1. 從mainBundle載入22         NSBundle *bundle = [NSBundle mainBundle];23         NSString *path = [bundle pathForResource:@"app.plist" ofType:nil];24         _appList = [NSArray arrayWithContentsOfFile:path];25         26         NSLog(@"%@", _appList);27     }28     return _appList;29 }30 31 - (void)viewDidLoad32 {33     [super viewDidLoad];34     35     // 總共有3列36     int totalCol = 3;37     CGFloat viewW = 80;38     CGFloat viewH = 90;39     40     CGFloat marginX = (self.view.bounds.size.width - totalCol * viewW) / (totalCol + 1);41     CGFloat marginY = 10;42     CGFloat startY = 20;43     44     for (int i = 0; i < self.appList.count; i++) {45 46         int row = i / totalCol;47         int col = i % totalCol;48         49         CGFloat x = marginX + (viewW + marginX) * col;50         CGFloat y = startY + marginY + (viewH + marginY) * row;51         52         UIView *appView = [[UIView alloc] initWithFrame:CGRectMake(x, y, viewW, viewH)];53       54         [self.view addSubview:appView];55         56         // 建立appView內部的細節57         // 0> 讀取數組中的字典58         NSDictionary *dict = self.appList[i];59         60         // 1> UIImageView61         UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, viewW, 50)];62         imageView.image = [UIImage imageNamed:dict[@"icon"]];63         imageView.contentMode = UIViewContentModeScaleAspectFit;64         [appView addSubview:imageView];65         66         // 2> UILabel67         UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.bounds.size.height, viewW, 20)];68         // 設定文字69         label.text = dict[@"name"];70         label.font = [UIFont systemFontOfSize:12.0];71         label.textAlignment = NSTextAlignmentCenter;72         73         [appView addSubview:label];74         75         // 3> UIButton76         // UIButtonTypeCustom和[[UIButton alloc] init]是等價的77         UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];78         button.frame = CGRectMake(15, 70, viewW - 30, 20);79         80         [button setTitle:@"下載" forState:UIControlStateNormal];81         // *** 不能使用如下代碼直接設定title82 //        button.titleLabel.text = @"下載";83         // @property中readonly表示不允許修改對象的指標地址,但是可以修改對象的屬性84         button.titleLabel.font= [UIFont systemFontOfSize:14.0];85         86         [button setBackgroundImage:[UIImage imageNamed:@"buttongreen"] forState:UIControlStateNormal];87         [button setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"] forState:UIControlStateHighlighted];88         89         [appView addSubview:button];90     }91 }92 93 @end

3.實現效果

4.代碼問題

在上述代碼的第62,69行,我們是直接通過字典的鍵名擷取plist中的資料資訊,在viewController中需要直接和資料打交道,如果需要多次使用可能會因為不小心把鍵名寫錯,而程式並不報錯。鑒於此,可以考慮把字典資料轉換成一個模型,把資料封裝到一個模型中去,讓viewController不再直接和資料打交道,而是和模型互動。

一般情況下,設定資料和取出資料都使用“字串類型的key”,編寫這些key時,編輯器沒有智能提示,需要手敲。如:

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

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

手敲字串key,key容易寫錯

Key如果寫錯了,編譯器不會有任何警告和報錯,造成設錯資料或者取錯資料

二、字典轉模型

1.字典轉模型介紹

 

字典轉模型的好處:

(1)降低代碼的耦合度

(2)所有字典轉模型部分的代碼統一集中在一處處理,降低代碼出錯的幾率

(3)在程式中直接使用模型的屬性操作,提高編碼效率 

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

字典轉模型的注意點:

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

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

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

提示:在模型中合理地使用唯讀屬性,可以進一步降低代碼的耦合度。

 

 2.程式碼範例(一)

建立一個類,用來作為資料模型

viewController.m檔案代碼(字典轉模型)

  1 #import "LFViewController.h"  2 #import "LFAppInfo.h"  3   4 @interface LFViewController ()  5 @property (nonatomic, strong) NSArray *appList;  6 @end  7   8 @implementation LFViewController  9  10 // 字典轉模型 11 - (NSArray *)appList 12 { 13     if (!_appList) { 14         // 1. 從mainBundle載入 15         NSBundle *bundle = [NSBundle mainBundle]; 16         NSString *path = [bundle pathForResource:@"app.plist" ofType:nil]; 17 //        _appList = [NSArray arrayWithContentsOfFile:path]; 18          19         NSArray *array = [NSArray arrayWithContentsOfFile:path]; 20         // 將數群組轉換成模型,意味著self.appList中儲存的是LFAppInfo對象 21         // 1. 遍曆數組,將數組中的字典依次轉換成AppInfo對象,添加到一個臨時數組 22         // 2. self.appList = 臨時數組 23  24         NSMutableArray *arrayM = [NSMutableArray array]; 25         for (NSDictionary *dict in array) { 26            //用字典來執行個體化對象的Factory 方法 27             [arrayM addObject:[LFAppInfo appInfoWithDict:dict]]; 28         } 29          30         _appList = arrayM; 31     } 32     return _appList; 33 } 34  35 - (void)viewDidLoad 36 { 37     [super viewDidLoad]; 38      39     // 總共有3列 40     int totalCol = 3; 41     CGFloat viewW = 80; 42     CGFloat viewH = 90; 43      44     CGFloat marginX = (self.view.bounds.size.width - totalCol * viewW) / (totalCol + 1); 45     CGFloat marginY = 10; 46     CGFloat startY = 20; 47      48     for (int i = 0; i < self.appList.count; i++) { 49  50         int row = i / totalCol; 51         int col = i % totalCol; 52          53         CGFloat x = marginX + (viewW + marginX) * col; 54         CGFloat y = startY + marginY + (viewH + marginY) * row; 55          56         UIView *appView = [[UIView alloc] initWithFrame:CGRectMake(x, y, viewW, viewH)]; 57          58         [self.view addSubview:appView]; 59          60         // 建立appView內部的細節 61         // 0> 讀取數組中的AppInfo 62 //        NSDictionary *dict = self.appList[i]; 63         LFAppInfo *appInfo = self.appList[i]; 64          65         // 1> UIImageView 66         UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, viewW, 50)]; 67         imageView.image = appInfo.image; 68         imageView.contentMode = UIViewContentModeScaleAspectFit; 69          70         [appView addSubview:imageView]; 71          72         // 2> UILabel 73         UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.bounds.size.height, viewW, 20)]; 74         // 設定文字 75         label.text = appInfo.name; 76         label.font = [UIFont systemFontOfSize:12.0]; 77         label.textAlignment = NSTextAlignmentCenter; 78          79         [appView addSubview:label]; 80          81         // 3> UIButton 82         // UIButtonTypeCustom和[[UIButton alloc] init]是等價的 83         UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 84         button.frame = CGRectMake(15, 70, viewW - 30, 20); 85          86         [button setTitle:@"下載" forState:UIControlStateNormal]; 87         button.titleLabel.font= [UIFont systemFontOfSize:14.0]; 88          89         [button setBackgroundImage:[UIImage imageNamed:@"buttongreen"] forState:UIControlStateNormal]; 90         [button setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"] forState:UIControlStateHighlighted]; 91          92         [appView addSubview:button]; 93         button.tag = i; 94          95         [button addTarget:self action:@selector(downloadClick:) forControlEvents:UIControlEventTouchUpInside]; 96     } 97 } 98  99 - (void)downloadClick:(UIButton *)button100 {101     NSLog(@"%d", button.tag);102     // 執行個體化一個UILabel顯示在視圖上,提示使用者下載完成103     UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(80, 400, 160, 40)];104     label.textAlignment = NSTextAlignmentCenter;105     label.backgroundColor = [UIColor lightGrayColor];106     107     LFAppInfo *appInfo = self.appList[button.tag];108     label.text = [NSString stringWithFormat:@"下載%@完成", appInfo.name];109     label.font = [UIFont systemFontOfSize:13.0];110     label.alpha = 1.0;111     [self.view addSubview:label];112     113     // 動畫效果114     // 動畫效果完成之後,將Label從視圖中刪除115     // 首尾式動畫,只能做動畫,要處理完成後的操作不方便116 //    [UIView beginAnimations:nil context:nil];117 //    [UIView setAnimationDuration:1.0];118 //    label.alpha = 1.0;119 //    [UIView commitAnimations];120 121     // block動畫比首尾式動畫簡單,而且能夠控制動畫結束後的操作122     // 在iOS中,基本都使用首尾式動畫123     [UIView animateWithDuration:2.0 animations:^{124         label.alpha = 0.0;125     } completion:^(BOOL finished) {126         // 刪除label127         [label removeFromSuperview];128     }];129 }130 131 @end

模型.h檔案代碼

 1 #import <Foundation/Foundation.h> 2  3 @interface LFAppInfo : NSObject 4  5 // 應用程式名稱 6 @property (nonatomic, copy) NSString *name; 7 // 應用程式圖示名稱 8 @property (nonatomic, copy) NSString *icon; 9 10 // 映像11 // 定義屬性時,會產生getter&setter方法,還會產生一個帶底線的成員變數12 // 如果是readonly屬性,只會產生getter方法,同時沒有成員變數13 @property (nonatomic, strong, readonly) UIImage *image;14 15 // instancetype會讓編譯器檢查執行個體化對象的準確類型16 // instancetype只能用於傳回型別,不能當做參數使用17 18 - (instancetype)initWithDict:(NSDictionary *)dict;19 /** Factory 方法 */20 + (instancetype)appInfoWithDict:(NSDictionary *)dict;21 22 @end

模型.m檔案資料處理代碼

 1 #import "LFAppInfo.h" 2  3 @interface LFAppInfo() 4 { 5     UIImage *_imageABC; 6 } 7 @end 8  9 @implementation LFAppInfo10 11 - (instancetype)initWithDict:(NSDictionary *)dict12 {13     self = [super init];14     if (self) {15         self.name = dict[@"name"];16         self.icon = dict[@"icon"];17     }18     return self;19 }20 21 + (instancetype)appInfoWithDict:(NSDictionary *)dict22 {23     return [[self alloc] initWithDict:dict];24 }25 26 - (UIImage *)image27 {28     if (!_imageABC) {29         _imageABC = [UIImage imageNamed:self.icon];30     }31     return _imageABC;32 }33 34 @end

3.程式碼範例(二)

資料資訊:plist檔案

字典轉模型(初步)

模型.h檔案

 1 #import <Foundation/Foundation.h> 2  3 @interface LFQuestion : NSObject 4  5 @property (nonatomic, copy) NSString *answer; 6 @property (nonatomic, copy) NSString *title; 7 @property (nonatomic, copy) NSString *icon; 8 @property (nonatomic, strong) NSArray *options; 9 10 @property (nonatomic, strong) UIImage *image;11 12 /** 用字典執行個體化對象的成員方法 */13 - (instancetype)initWithDict:(NSDictionary *)dict;14 /** 用字典執行個體化對象的類方法,又稱Factory 方法 */15 + (instancetype)questionWithDict:(NSDictionary *)dict;16 @end

模型.m檔案

 1 #import "LFQuestion.h" 2  3 @implementation LFQuestion 4  5 + (instancetype)questionWithDict:(NSDictionary *)dict 6 { 7     return [[self alloc] initWithDict:dict]; 8 } 9 10 - (instancetype)initWithDict:(NSDictionary *)dict11 {12     self = [super init];13     if (self) {14         self.answer = dict[@"answer"];15         self.icon = dict[@"icon"];16         self.title = dict[@"title"];17         self.options = dict[@"options"];18 19         [self setValuesForKeysWithDictionary:dict];20     }21     return self;22 }

viewController.m檔案中的資料處理

 1 - (NSArray *)questions 2 { 3     if (!_questions) { 4      5         NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"questions.plist" ofType:nil]]; 6          7         NSMutableArray *arrayM = [NSMutableArray array]; 8          9         for (NSDictionary *dict in array) {10             [arrayM addObject:[LFQuestion questionWithDict:dict]];11         }12         _questions=arrayM;13     }14     return _questions;15 }

字典轉模型(最佳化)

上面代碼可以做進一步的最佳化,從plist檔案中讀取資料是可以交給模型去處理的,最佳化後代碼如下:

模型.h檔案

 1 #import <Foundation/Foundation.h> 2  3 @interface LFQuestion : NSObject 4  5 @property (nonatomic, copy) NSString *answer; 6 @property (nonatomic, copy) NSString *title; 7 @property (nonatomic, copy) NSString *icon; 8 @property (nonatomic, strong) NSArray *options; 9 10 @property (nonatomic, strong) UIImage *image;11 12 /** 用字典執行個體化對象的成員方法 */13 - (instancetype)initWithDict:(NSDictionary *)dict;14 /** 用字典執行個體化對象的類方法,又稱Factory 方法 */15 + (instancetype)questionWithDict:(NSDictionary *)dict;16 17 /** 從plist載入對象數組 */18 + (NSArray *)questions;19 20 @end

模型.m檔案

 1 #import "LFQuestion.h" 2  3 @implementation LFQuestion 4  5 + (instancetype)questionWithDict:(NSDictionary *)dict 6 { 7     return [[self alloc] initWithDict:dict]; 8 } 9 10 - (instancetype)initWithDict:(NSDictionary *)dict11 {12     self = [super init];13     if (self) {14         self.answer = dict[@"answer"];15         self.icon = dict[@"icon"];16         self.title = dict[@"title"];17         self.options = dict[@"options"];18         19         [self setValuesForKeysWithDictionary:dict];20     }21     return self;22 }23 24 25 + (NSArray *)questions26 {27     NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"questions.plist" ofType:nil]];28     29     NSMutableArray *arrayM = [NSMutableArray array];30     31     for (NSDictionary *dict in array) {32         [arrayM addObject:[LFQuestion questionWithDict:dict]];33     }34     35     return arrayM;36 }37 @end

viewController.m檔案中的資料處理代碼部分

1 - (NSArray *)questions2 {3     if (!_questions) {4         _questions = [LFQuestion questions];5     }6     return _questions;7 }

補充內容:(KVC)的使用

(1)在模型內部的資料處理部分,可以使用索引值編碼來進行處理

 1 - (instancetype)initWithDict:(NSDictionary *)dict 2 { 3     self = [super init]; 4     if (self) { 5 //        self.answer = dict[@"answer"]; 6 //        self.icon = dict[@"icon"]; 7 //        self.title = dict[@"title"]; 8 //        self.options = dict[@"options"]; 9         10         // KVC (key value coding)索引值編碼11         // cocoa 的大招,允許間接修改對象的屬性值12         // 第一個參數是字典的數值13         // 第二個參數是類的屬性14         [self setValue:dict[@"answer"] forKeyPath:@"answer"];15         [self setValue:dict[@"icon"] forKeyPath:@"icon"];16         [self setValue:dict[@"title"] forKeyPath:@"title"];17         [self setValue:dict[@"options"] forKeyPath:@"options"];18     }19     return self;20 }

(2)setValuesForKeys的使用

上述資料操作細節,可以直接通過setValuesForKeys方法來完成。

1 - (instancetype)initWithDict:(NSDictionary *)dict2 {3     self = [super init];4     if (self) {5         // 使用setValuesForKeys要求類的屬性必須在字典中存在,可以比字典中的索引值多,但是不能少。6         [self setValuesForKeysWithDictionary:dict];7     }8     return self;9 }

三、補充說明

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的真實類型

 

  

iOS開發UI篇—字典轉模型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.