For a long time did not write the article, the previous article for beginners may be more useful ...
My language is Java, JSP, more emphasis on the MVC pattern, so the MVC is still relatively understanding. So later into iOS development, in the pattern is not so tangled, but for many beginners in the field of programming may be more confused, the following a simple list of examples of iOS development in the MVC pattern.
First, create a new project and create a new subclass of two Uiviewcontroller in the project,
I'm going to use these two classes to sample non-MVC (Mainviewcontroller) and MVC (Secondviewcontroller) patterns, for readability and for more explanatory purposes, without IB in the example, all the interfaces written in code (which is also my personal development habit).
Where the MAINVIEWCONTROLLER.M code is as follows
#import "MainViewController.h" #import "ASIFormDataRequest.h" #define Kscreenwidth [UIScreen mainscreen]. Bounds.size.width#define kscreenheight [UIScreen mainscreen].bounds.size.height@interface MainViewController () @ Property (Nonatomic, retain) Nsmutablearray *dataarray; @end @implementation Mainviewcontroller {uitableview *_tableVie W;} -(void) viewdidload {[Super viewdidload]; [Self setupdefaultvalue]; [Self setupdefaultview]; [Self request];} -(void) Setupdefaultvalue {self.dataarray = [Nsmutablearray array];} -(void) Setupdefaultview {_tableview = [[UITableView alloc] Initwithframe:cgrectmake (0, 0, Kscreenwidth, kscreenheight ) Style:uitableviewstyleplain]; _tableview.delegate = self; _tableview.datasource = self; [Self.view Addsubview:_tableview];} -(void) Request {NSString *urlstring = @ "http://beautifulword.sinaapp.com/results.php"; Nsurl *url = [Nsurl urlwithstring:urlstring]; Asiformdatarequest *_request = [Asiformdatarequest requestWithurl:url]; __weak asiformdatarequest *request = _request; [Request setcompletionblock:^{NSData *data = request.responsedata; Nsdictionary *dict = [nsjsonserialization jsonobjectwithdata:data options:0 Error:nil]; Nsarray *array = [dict objectforkey:@ "Profile"]; For (nsdictionary *itemdict in array) {[Self.dataarray addobject:itemdict]; } [_tableview Reloaddata]; }]; [Request setfailedblock:^{NSLog (@ "failed"); }]; [Request startasynchronous];} #pragma mark-uitableview delegate-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) section {return self.dataArray.count;} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath {static Nsstri ng *cellid = @ "Cell"; UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:cellid]; if (cell = = nil) {cell = [[UITableViewCell alloc] Initwithstyle:uitabLeViewCellStyleValue1 Reuseidentifier:cellid]; } nsdictionary *dict = Self.dataarray[indexpath.row]; Cell.textLabel.text = dict[@ "name"]; Cell.detailTextLabel.text = dict[@ "Age"]; return cell;} -(void) didreceivememorywarning {[Super didreceivememorywarning];} @end
The class is simple, with three parts: initialization properties-Initialization interface-a list of network request refreshes.
For the MVC pattern, the most important thing is the controller, in the iOS project, we can easily find it, from the name can be seen, such as Mainviewcontroller, as to its role, can be found in the official Apple development document:
View controllers is the foundation of your app ' s internal structure. The Every app has an at least one view controller, and the most apps are several. Each view controller manages a portion of your app's user interface as well as the interactions between that interface and The underlying data. View controllers also facilitate transitions between different parts of your user interface.
In simple terms, management interface, data, and management interface and interface transformation, management interface and data interaction. We can see from the interface, data initialization to network requests are in the controller, if the interface and data is particularly complex, this class may reach thousands of lines, maintenance will be particularly troublesome, the most exaggerated possible tableView: Cellforrowatindexpath: There are hundreds of rows of methods. This is when the MVC pattern shows its advantages, and we separate the logic, the data, and the interface so that it becomes very easy to maintain.
Let's look at Mainviewcontroller, this class is very simple, logic is very clear, where model is the network request data, view is UITableView and UITableViewCell. The first step is to split the model first, and we create a new model class:
The UserModel.h file is as follows:
#import <Foundation/Foundation.h> @interface usermodel:nsobject@property (nonatomic, copy) NSString *name;@ Property (nonatomic, copy) NSString *age; @property (nonatomic, copy) NSString *gender; @property (nonatomic, copy) Nsstrin g *phone; @property (nonatomic, retain) nsmutabledictionary *dict; @end
The USERMODE.M file is as follows:
#import "UserModel.h" @implementation usermodel-(ID) init { if (self = = [Super init]) { self.dict = [[Nsmutabledic Tionary alloc] init]; } return self;} -(ID) Valueforundefinedkey: (NSString *) key { return @ "";} -(void) SetValue: (ID) value Forundefinedkey: (NSString *) key { [self.dict setobject:value forkey:key];} @end
This class is simple and contains only a few properties. Then we modify the request method in Mainviewcontroller as follows:
-(void) Request { NSString *urlstring = @ "http://beautifulword.sinaapp.com/results.php"; Nsurl *url = [Nsurl urlwithstring:urlstring]; Asiformdatarequest *_request = [Asiformdatarequest requestwithurl:url]; __weak asiformdatarequest *request = _request; [Request setcompletionblock:^{ NSData *data = request.responsedata; Nsdictionary *dict = [nsjsonserialization jsonobjectwithdata:data options:0 Error:nil]; Self.dataarray = [dict objectforkey:@ "Profile"]; [_tableview reloaddata]; }]; [Request setfailedblock:^{ NSLog (@ "failed"); }]; [Request startasynchronous];} -(void) Setdataarray: (Nsmutablearray *) DataArray {for (nsdictionary *itemdict in DataArray) { Usermodel * model = [[Usermodel alloc] init]; For (NSString *key in itemdict) { [model Setvalue:itemdict[key] forkey:key]; } [_dataarray Addobject:model];} }
As you can see, the DataArray is not saved in dictionary, but Usermodel. Of course, this example is relatively simple, usermodel internal does not involve more complex data processing, so does not reflect its advantages, but in the future development, this will certainly be more effective. Next, the view is split, in the Mainviewcontroller the code to initialize the cell is as follows (here for convenience, only name and age two attributes are written):
In general, I am accustomed to customizing the cell for later maintenance, next, create a new Tableviewcell subclass Usercell,.h file as follows:
#import <UIKit/UIKit.h> #import "UserModel.h" @interface Usercell:uitableviewcell@property (nonatomic, retain) Usermodel *model; @end
USERCELL.M files are as follows
#import "UserCell.h" #define Kscreenwidth [UIScreen mainscreen].bounds.size.width#define kscreenheight [UIScreen Mainscreen].bounds.size.height@implementation Usercell {UILabel *_namelabel; UILabel *_agelabel; UILabel *_genderlabel; UILabel *_phonelabel;} -(void) awakefromnib {}-(Usercell *) Initwithstyle: (Uitableviewcellstyle) style Reuseidentifier: (NSString *) reuseidentifier {self = [super Initwithstyle:style reuseidentifier:reuseidentifier]; if (self) {_namelabel = [[UILabel alloc] Initwithframe:cgrectmake (0, 0, KSCREENWIDTH/4, 40)]; _namelabel.textcolor = [Uicolor blackcolor]; _namelabel.textalignment = Nstextalignmentcenter; [Self.contentview Addsubview:_namelabel]; _agelabel = [[UILabel alloc] Initwithframe:cgrectmake (KSCREENWIDTH/4, 0, KSCREENWIDTH/4, 40)]; _agelabel.textcolor = [Uicolor blackcolor]; _agelabel.textalignment = Nstextalignmentcenter; [Self.contentview Addsubview:_agelabel]; _genderlabel = [[UILabel alloc] Initwithframe:cgrectmake (kscreenwidth/4*2, 0, KSCREENWIDTH/4/2, 40)]; _genderlabel.textcolor = [Uicolor blackcolor]; _genderlabel.textalignment = Nstextalignmentcenter; [Self.contentview Addsubview:_genderlabel]; _phonelabel = [[UILabel alloc] Initwithframe:cgrectmake (KSCREENWIDTH/4*3-KSCREENWIDTH/4/2, 0, kscreenwidth/4+ KSCREENWIDTH/4/2, 40)]; _phonelabel.textcolor = [Uicolor blackcolor]; _phonelabel.textalignment = Nstextalignmentcenter; [Self.contentview Addsubview:_phonelabel]; } return self;} -(void) setselected: (BOOL) selected animated: (bool) animated {[Super setselected:selected animated:animated];} -(void) Setmodel: (Usermodel *) Model {_model = model; _namelabel.text = Model.name; _agelabel.text = Model.age; _genderlabel.text = Model.gender; _phonelabel.text = Model.phone;} @end
The initialization of the cell, it is encapsulated in the Usercell class, Mainviewcontroller in the Tableview:cellforrowatindex: The method is changed to the following:
-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath { static NSString *cellid = @ "cell"; Usercell *cell = [TableView dequeuereusablecellwithidentifier:cellid]; if (cell = = nil) { cell = [[Usercell alloc] Initwithstyle:uitableviewcellstyledefault reuseidentifier:cellid]; } Cell.model = Self.dataarray[indexpath.row]; return cell;}
So, when we need to adjust the cell layout, there is no need to modify the Mainviewcontroller class, just need to find the Usercell adjustment.
After the MVC separation is complete, organize the code into another class Secondviewcontroller, as follows:
#import "SecondViewController.h" #import "ASIFormDataRequest.h" #import "UserModel.h" #import "UserCell.h" #define kscreenwidth [UIScreen mainscreen].bounds.size.width#define kscreenheight [UIScreen mainScreen].bounds.size.height@ Interface Secondviewcontroller () @property (nonatomic, retain) Nsmutablearray *dataarray; @end @implementation Secondviewcontroller {UITableView *_tableview;} -(void) viewdidload {[Super viewdidload]; [Self setupdefaultvalue]; [Self setupdefaultview]; [Self request];} -(void) Setupdefaultvalue {_dataarray = [Nsmutablearray array];} -(void) Setupdefaultview {_tableview = [[UITableView alloc] Initwithframe:cgrectmake (0, 0, Kscreenwidth, kscreenheight ) Style:uitableviewstyleplain]; _tableview.delegate = self; _tableview.datasource = self; [Self.view Addsubview:_tableview];} -(void) Request {NSString *urlstring = @ "http://beautifulword.sinaapp.com/results.php"; Nsurl *url = [Nsurl urlwithstring:urlstring]; AsiformdatarequEST *_request = [asiformdatarequest Requestwithurl:url]; __weak asiformdatarequest *request = _request; [Request setcompletionblock:^{NSData *data = request.responsedata; Nsdictionary *dict = [nsjsonserialization jsonobjectwithdata:data options:0 Error:nil]; Self.dataarray = [dict objectforkey:@ "Profile"]; [_tableview Reloaddata]; }]; [Request setfailedblock:^{NSLog (@ "failed"); }]; [Request startasynchronous];} #pragma mark-uitableview delegate-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) section {return self.dataArray.count;} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath {static Nsstri ng *cellid = @ "Cell"; Usercell *cell = [TableView dequeuereusablecellwithidentifier:cellid]; if (cell = = nil) {cell = [[Usercell alloc] Initwithstyle:uitableviewcellstyledefault reuseidentifier:cellid]; } Cell.model = Self.daTaarray[indexpath.row]; return cell;} -(void) Setdataarray: (Nsmutablearray *) DataArray {for (nsdictionary *itemdict in DataArray) {Usermodel *model = [[Usermodel alloc] init]; For (NSString *key in itemdict) {[model Setvalue:itemdict[key] forkey:key]; } [_dataarray Addobject:model]; }} @end
OK, the whole introduction to this end, about the theoretical knowledge of MVC, but also please Baidu itself.
Example Source address: Mvctest on GitHub
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
MVC of iOS development