iOS Development UI Chapter-MVC from the gradual optimization of code

Source: Internet
Author: User

iOS Development UI Chapter-MVC from the gradual optimization of code

First, the requirements

Request to complete the following small application.

Two or one steps to optimize your code

Note: During the development process, the optimization process is step-by-step. (If a person to eat five steamed buns to eat full, then whether he ate the fifth directly, the front four without eating is full?) )

1. Code to complete the basic requirements (using the dictionary to model and Xib connection)

(1) File structure

(2) Main code

Dictionary to model section:

YYappInfo.h header File

8  9 #import <foundation/foundation.h>10 @interface yyappinfo:nsobject12 @property (nonatomic,copy) NSString *name;13 @property (nonatomic,copy) nsstring *icon;14 @property (nonatomic,strong,readonly) UIImage *img;15 16- (instancetype) Initwithdict: (nsdictionary *) dict;17/** Factory method */18 + (Instancetype) appinfowithdict: (NSDictionary *) dict ; @end

YYAPPINFO.M file

8  9 #import "YYappInfo.h" @interface Yyappinfo () {     UIImage *_img;13}14 @end15 @implementation YYappInfo16 -(Instancetype) Initwithdict: (Nsdictionary *) dict17 {     (self=[super init]) {         self.name=dict[@ "name"];         self.icon=dict[@ "icon"];21     }22     return self;23}24 + (instancetype) appinfowithdict: (Nsdictionary *) dict26 {[Self     alloc]initwithdict:dict];28}29-(UIImage *) img31 {_img=[uiimage imagenamed     : self.icon];33     return _img;34}35 @end

Xib section (YYappInfoView.h file):

Note: (The Xib view is associated with the Yyappinfoview and all three properties are wired)

8  9 #import <uikit/uikit.h>10 @interface yyappinfoview:uiview12 @property (Strong, nonatomic) Iboutlet Uiim Ageview *appinfoviewimg;13 @property (Strong, nonatomic) Iboutlet UILabel *appinfoviewlab;15 @property (Strong, Nonato MIC) Iboutlet UIButton *appinfoviewbtn;16 @end

Main Feature Implementation section:

YYVIEWCONTROLLER.M file

 8 9 #import "YYViewController.h" #import "YYappInfo.h" #import "YYappInfoView.h" @interface Yyviewcontroller () @property (Nonatomic,strong) nsarray *apps;15 @end16 17//Development ideas 18//1. Load plist file (dictionary to model provides interface) 19//2. Use the Xib file to complete a single view20// 3. Calculate the coordinates and use the for loop to display the view to the interface 21//4. Optimize code @implementation YYViewController23//get method, lazy load-(Nsarray *) Apps26 {if ( !_apps) {NSString *path = [[NSBundle mainbundle]pathforresource:@ ' app.plist ' oftype:nil];29 NSArray * A Rraym = [Nsarray arraywithcontentsoffile:path];30 nsmutablearray *appinfoarray=[nsmutablearray array];3         2 for (Nsdictionary *dict in Arraym) {Appinfoarray addobject:[yyappinfo appinfowithdict:dict]];34 }35 _apps = appinfoarray;36}37 return _apps;38}39-(void) viewDidLoad41 {[Super Viewdi dload];43 NSLog (@ "%d", self.apps.count), int totalloc = 3;46 cgfloat appvieww = 80;47 cgfloat APPV IEWH = 90;48 cgfloat Margin = (SELF.VIEW.FRAME.SIZE.WIDTH-TOTALLOC*APPVIEWW)/(totalloc+1), a. int count=self.apps.count;51 for (int i = 0; I < count; i++) {A. int row = i/totalloc;53 int loc = i%totalloc;54 CGFloat appviewx = margin + (m Argin + appvieww) * loc;56 cgfloat appviewy = margin + (margin + appviewh) * row;57 + Yyappinf o *appinfo=self.apps[i];59 60//Take out data in Xib nsarray *arrym=[[nsbundle mainbundle]loadnibnamed:@ "AP Pinfoxib "Owner:nil options:nil];62 yyappinfoview *appinfoview=[arrym firstobject];63//Set Location app Infoview.frame=cgrectmake (Appviewx, Appviewy, APPVIEWW, APPVIEWH); 65//Set Value: appinfoview.appInfoViewimg.im age=appinfo.img;67 appinfoview.appinfoviewlab.text=appinfo.name;68//Add to view Appinfoview.appinfovi ewbtn.tag=i;70 [appinfoview.appinfoviewbtn addtarget:self Action: @selector (Click:) forcontrolevents:uicontrolevent Touchupinside];71 [Self.view addsubview:appinfoview];72}73}74-(void) Click: (UIButton *) btn75 {btn.enable d=no;77 yyappinfo *appinfo=self.apps[btn.tag];78 UILabel *lab=[[uilabel alloc]initwithframe:cgrectmake (60, 450, 20     0,];79 [lab setbackgroundcolor:[uicolor lightgraycolor]];80 [Lab settextalignment:nstextalignmentcenter];81 [Lab settext:[nsstring stringwithformat:@ "%@ successfully downloaded", appinfo.name]];82 [self.view addsubview:lab];83 + Lab.alp         ha=1.0;85 [UIView animatewithduration:2.0 animations:^{86 lab.alpha=0;87}completion:^ (BOOL finished) {88 [Lab removefromsuperview];89}];90}91 @end

2. Optimize for 1 (encapsulate the data presentation part into the view)

Description: Search on the basis of 1 and there will be parts that can be optimized

1) Ideas for improvement:

(1) The 66~67 of the main file in 1 can the settings of the control properties be taken in the view?

(2) 1 The 61~62 line is the operation that reads information from the Xib file, and there is not much association with the host controller, can it also be encapsulated in the view?

(3) When the above two steps completed, the main file 69 line after the button action and button click event is very abrupt, placed in the host controller is no longer appropriate, can be put in the view to be processed

2) Follow the above ideas to optimize the code as follows:

An optimized view that provides an interface to the outside of the view section to encapsulate data processing in-house

YYappInfoView.h File Code:

8  9 #import <uikit/uikit.h>10 @class yyappinfo;11 @interface yyappinfoview:uiview12 13//Read//+ (Instancetyp e) appinfoview;15//Open only one Data interface (Instancetype) Appinfoviewwithappinfo: (Yyappinfo *) appinfo;17 @end

YYAPPINFOVIEW.M File Code

Note: The properties in the file and the click are all connected.

 8 9 #import "YYappInfoView.h" #import "YYappInfo.h" 11//private extension, bring the attributes in @interface Yyappinfoview () @property (St Rong, nonatomic) iboutlet Uiimageview *appinfoviewimg;14 @property (Strong, nonatomic) Iboutlet UILabel *appinfoviewlab; @property (Strong, nonatomic) Iboutlet UIButton *appinfoviewbtn;16 @property (strong,nonatomic) Yyappinfo *appinfo;17 @end19 @implementation YYappInfoView20 + (instancetype) appInfoView22 {nsarray *arrym=[[nsbundle Mainbundle]loa dnibnamed:@ "Appinfoxib" Owner:nil options:nil];24 yyappinfoview *appinfoview=[arrym firstObject];25 return appinfo View;26}27 + (instancetype) Appinfoviewwithappinfo: (Yyappinfo *) appinfo29 {Yyappinfoview *appinfoview=[self appIn foview];31 appinfoview.appinfo=appinfo;32 return appinfoview;33}34-(void) Setappinfo: (Yyappinfo *) appinfoc36 { 37//Here Be sure to record changes of _appinfo=appinfoc;39 self.appinfoviewimg.image=appinfoc.img; 
Self.appinfoviewlab.text=appinfoc.name;
41}
-(Ibaction) Click {     self.appinfoviewbtn.enabled=no;45     //yyappinfo *appinfo=self.apps[];46     yyappinfo *appinfo=self.appinfo;48     UILabel *lab=[[uilabel alloc]initwithframe:cgrectmake (60, 450, 200, 20 )];49     [Lab setbackgroundcolor:[uicolor lightgraycolor]];50     [Lab Settextalignment:nstextalignmentcenter];     [Lab settext:[nsstring stringwithformat:@ "%@ successfully downloaded", appinfo.name]];52     //Add Lab to Parent view (i.e. view)     [ Self.superview addsubview:lab];54     lab.alpha=1.0;56     [UIView animatewithduration:2.0 animations:^ {         lab.alpha=0;58     }completion:^ (BOOL finished) {         [lab removefromsuperview];60     }];61}62 63 64 @end

Optimized Master Controller Section

YYVIEWCONTROLLER.M File Code

 8 9 #import "YYViewController.h" #import "YYappInfo.h" #import "YYappInfoView.h" @interface Yyviewcontroller () @property (Nonatomic,strong) nsarray *apps;15 @end16 @implementation YYViewController17-(Nsarray *) Apps19 {if (!_apps) {NSString *path = [[NSBundle mainbundle]pathforresource:@ "App.plist" oftype:nil];22 nsarray * ArrayM =         [Nsarray arraywithcontentsoffile:path];23 Nsmutablearray *appinfoarray=[nsmutablearray array];25         For (Nsdictionary *dict in Arraym) {[Appinfoarray addobject:[yyappinfo appinfowithdict:dict]];27 }28 _apps = appinfoarray;29}30 return _apps;31}32-(void) viewDidLoad34 {[Super Viewdidload];3 6 NSLog (@ "%d", self.apps.count), PNs int totalloc = 3;39 cgfloat appvieww = 80;40 cgfloat APPVIEWH = 9 0;41 cgfloat margin = (self.view.frame.size.width-totalloc*appvieww)/(totalloc+1); int count=self.apps.co Unt;44 for(int i = 0; i < count; i++)  {int row = i/totalloc;46 int loc = i%totalloc;47 CGFloat appviewx = margin + (margin          + appvieww) * loc;49 cgfloat appviewy = margin + (margin + appviewh) * ROW;50 51/* Ideas: 52 To achieve the effect of appinfoview.appinfo=appinfo;53 optimization becomes appinfoview.appinfo=self.apps[i];54 to do the above code, you need to add a new in the view The AppInfo class's properties, so that the data--"view of the conversion can not need to be completed in the master controller, the program structure at a glance */56 yyappinfo *appinfo=self.apps[i];57 Yyappi Nfoview *appinfoview=[yyappinfoview appinfoviewwithappinfo:appinfo];58//Set Location Appinfoview.frame=cgrectma Ke (appviewx, appviewy, APPVIEWW, APPVIEWH); 60//Add to [Self.view addsubview:appinfoview];62}63}64 @en D

3. Further optimization of 2 (take the data processing part to the model)

(1) Thinking: The Dictionary to the model part of the data processing operations, get the model to deal with, so that the outside world does not need to care about the internal details of data processing.

(2) The optimized code is as follows

An interface is opened outward in the YYappInfo.h file, returning a well-handled array.

1  8  9 #import <foundation/foundation.h>10 @interface yyappinfo:nsobject12 @property (nonatomic,copy) NSString *name;13 @property (nonatomic,copy) nsstring *icon;14 @property (nonatomic,strong) UIImage *img;15 16-( Instancetype) Initwithdict: (nsdictionary *) dict;17/** Factory method */18 + (Instancetype) appinfowithdict: (NSDictionary *) dict; + (Nsarray *) appinfoarray;20 @end

Data processing in the YYAPPINFO.M file

  8  9 #import "YYappInfo.h" @interface yyappinfo () @end12 @implementation YYappInfo13-(instancetype) Initwithdict: (nsdictionary *) dict14 {     if (self=[super init]) {self.name=dict[@         "name"];17 Self.icon         =dict[@ "icon"];18     }19     return self;20}21 (instancetype) appinfowithdict: (Nsdictionary *) dict23 {     return [[Self alloc]initwithdict:dict];25}26-(UIImage *) img28 {     _img=[uiimage imagenamed:self.icon];30     return _img;31}32 33//Take the Data Processing section to the model to handle the + (Nsarray *) appinfoarray35 {nsstring *path     = [[NSBundle Mainbundle]path forresource:@ "App.plist" oftype:nil];37     nsarray * Arraym = [Nsarray arraywithcontentsoffile:path];38     39     Nsmutablearray *appinfoarray=[nsmutablearray array];40 for     (nsdictionary *dict in Arraym) {         [ Appinfoarray addobject:[yyappinfo appinfowithdict:dict]];42     }43     return appinfoarray;44}45 @end

No longer need to care about the internal details of data processing in the host controller

The yyviewcontroller.m file is now only responsible for the coordination between the model and the view. That's almost it.

  8 9 #import "YYViewController.h" #import "YYappInfo.h" #import "YYappInfoView.h" @interface Yyviewcontroller (  ) @property (Nonatomic,strong) nsarray *apps;15 @end16 @implementation YYViewController17-(Nsarray *) Apps19 {if (!_apps) {_apps=[yyappinfo appinfoarray];22}23 return _apps;24}25-(void) ViewDidLoad27 {[Super view] didload];29 int totalloc = 3;31 cgfloat appvieww = 80;32 cgfloat appviewh = 90;33 cgfloat margin =  (SELF.VIEW.FRAME.SIZE.WIDTH-TOTALLOC*APPVIEWW)/(totalloc+1); int count=self.apps.count;36 for (int i = 0; I < count; i++) {PNs int row = i/totalloc;39 int loc = i%totalloc;40 CGFloat appviewx =         Margin + (margin + appvieww) * loc;42 cgfloat appviewy = margin + (margin + appviewh) * row;43 44 Yyappinfo *appinfo=self.apps[i];45 Yyappinfoview *appinfoview=[yyappinfoview appinfoviewwithappinfo:appinfo];46        Appinfoview.frame=cgrectmake (Appviewx, Appviewy, APPVIEWW, APPVIEWH); [Self.view Addsubview:appinfoview] ;}49}50 @end

Implementation results:

4. Additional Information

View Packaging Ideas

(1) If a view inside the child control is more, it is generally considered to customize a view, the creation of its internal sub-controls to screen up, do not let outside concern

(2) The outside world can pass the corresponding model data to the View,view to get the model data and set the corresponding data for the inner child control.

Three, the MVC mechanism simple explanation

Description

(1) In the development process, as the controller to deal with the magnitude should be very light, should not worry about not worry. Good coordination of models and views is OK, learn to be a good boss.

(2) Three parts of the work, the data model is only responsible for data processing, the view part is responsible for the data to be displayed, two parts are passive, waiting for the large Butler controller field.

(3) in OC, if there is a channel between the view and the data model, is the controller in a runaway state?

iOS Development UI Chapter-MVC from the gradual optimization of code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.