iOS Development > Learning-Talk about MVVM's architecture design and team collaboration

Source: Internet
Author: User

Li Gang Press: This article is green Jade at the desk wrote an article. Believing that you are familiar with MVC and that MVVM may have heard relatively little, this article will want you to elaborate on the MVVM design, as well as the experience sharing of team collaboration. If you feel good about it, share it!

Demo:Https://github.com/lizelu/MVVM

Today writing this article is to achieve a role, want to exchange ideas with you, learn from each other, there are shortcomings in the blog also hope that we criticize. The content of this article is based on the style of the past blog, but also dry-based, occasionally pull the salty egg (haha ~ not good work and began to publish blog ~).

Due to my limited project experience and limited understanding of the architecture design, my personal understanding of MVVM is mostly borrowed from the previous MVC web framework-used by the thinkphp framework in school, and the SSH framework, which are MVC's architectural patterns. Today's MVVM is very similar to the traditional MVC, and it can be said to be a sibling, a family.

When it comes to architecture design and teamwork, this is important for app development. Even as a professional brick-and-tile, if you put it in the end of the brick where? Not only the code has the framework, the other things are framed, such as bridges and so on God horse ~ here will not pull out. A good project framework can improve team collaboration efficiency, but also can reduce the redundancy and coupling of code, reasonable division of labor and system architecture design is indispensable.

As far as team collaboration is not just with SVN or Git version control tools, for how to use SVN in iOS development, refer to the previous blog (iOS development version Control (SVN)). A team can work efficiently, I feel that communication is the most important, everyone in the team is more pleasant, and communication is not any obstacle (but there are always a few people in the team), communication in the team is the most important. As for how SVN is used, it's not a thing!

All right, today, with a demo I wrote about the architecture design and teamwork in iOS development, today's salted eggs come here first and cut into today's topic.

In order to write today's blog I took a little time to do a project, the project backend interface with the Sina Weibo API to test, and later in this article will follow the GitHub share link. Ok~ said the tall on some is, the benevolent see, exchange ideas, learn together.

a drink of MVVM

In this, do not dwell on what is MVC, God horse is MVVM, Google on Baidu on a grab a lot, here simply put on a mouth. The following demo uses the schema mode of MVVM.

The model layer is indispensable, we have to have something to act as a DTO (data transfer object), of course, with a dictionary is also possible, programming, to be flexible. The model layer is a relatively thin layer, if you learn Java's small partners, JavaBean should not be unfamiliar with it.

The ViewModel layer, the binder for the view and model layers, is an excellent place to put user input validation logic, view display logic, initiating network requests, and a variety of other code. To put it bluntly, the original Viewcontroller layer of business logic and page logic and so stripped out to the ViewModel layer.

The view layer is the Viewcontroller layer, and his task is to get the data from the ViewModel layer and display it.

The above for MVVM on the first simple to say, good understanding and application, but also to combat.

Ii. discussion on whether to use storyboard in engineering

From the Internet often see that it is not recommended to use storyboard or xib, the recommendation of pure code handwriting. Personally think that this view and Apple design Storyboard contrary to the original intention, in the project I have done is mainly storyboard, xib supplemented, and then the code to integrate each storyboard.

To take a storyboard advantage of the example is OK, to add constraints to the control, if the use of storyboard to accomplish that is minutes and seconds, and the code to add constraints is how disgusting, pure code writing will spend a lot of time on the writing UI, and the technical content is relatively low, The man thought there was no need. The small partners responsible for UI development in team work just no one is responsible for a Storyboard, each development, with SVN submit the following tick (such as) to remove, so use Storyboard is no problem. Then the integration with the code is OK. If you have added a new resource file to your project, you will need to submit it with the project setting file if you submit it with Xcode's own SVN.

Third, actual combat MVVM

(the group created with Xcode is a virtual folder, it is recommended to create a physical folder for ease of maintenance, and then introduce it manually.)

1. Below is an example of the MVVM schema pattern, the following is the first level of the project directory below, each layer of interaction is implemented in the form of block

Project Catalog Description:

Request: The class that stores the network request under the folder, the following will give a specific implementation

Config: is the project configuration file

Resource: Is the project resource file, the following picture resources and storyboard file resources

Tools are: Tool file classes, storing tool classes, such as data regex matching.

Vender: Storage of third-party class libraries

Model: That's not much to say.

Viewcontroller: Store Viewcontroller class resource file, which is the view layer

ViewModel: Store various business logic and network requests

2. detailed request:request is responsible for the network request for things, as follows:

Netrequestclass is the code that holds the network request, this project uses the AF, because this project is only a demo, therefore only then encapsulates the monitoring network state, the GET request, the POST request method, according to the actual need, may also encapsulate uploads the download and so on the class method.

The code in NETREQUESTCLASS.H is as follows:

//

NetRequestClass.h

Mvvmtest

//

Created by Li Zeiru on 15/1/6.

Copyright (c) 2015 Li Zeiru. All rights reserved.

//

#import @interface Netrequestclass:nsobject

#pragma monitoring network for connectivity

+ (BOOL) networkreachabilitywithurlstring: (NSString *) strURL;

#pragma POST request

+ (void) Netrequestpostwithrequesturl: (NSString *) requesturlstring

Withparameter: (nsdictionary *) parameter

Withreturnvaleublock: (returnvalueblock) block

Witherrorcodeblock: (Errorcodeblock) Errorblock

Withfailureblock: (Failureblock) Failureblock;

#pragma GET request

+ (void) Netrequestgetwithrequesturl: (NSString *) requesturlstring

Withparameter: (nsdictionary *) parameter

Withreturnvaleublock: (returnvalueblock) block

Witherrorcodeblock: (Errorcodeblock) Errorblock

Withfailureblock: (Failureblock) Failureblock;

@end

The code in NETREQUESTCLASS.M is as follows:

//

Netrequestclass.m

Mvvmtest

//

Created by Li Zeiru on 15/1/6.

Copyright (c) 2015 Li Zeiru. All rights reserved.

//

#import "NetRequestClass.h"

@interface Netrequestclass ()

@end

@implementation Netrequestclass

#pragma monitoring network for connectivity

+ (BOOL) networkreachabilitywithurlstring: (NSString *) strURL

{

__block BOOL netstate = NO;

Nsurl *baseurl = [Nsurl Urlwithstring:strurl];

Afhttprequestoperationmanager *manager = [[Afhttprequestoperationmanager alloc] initwithbaseurl:baseurl];

Nsoperationqueue *operationqueue = Manager.operationqueue;

[Manager.reachabilitymanager setreachabilitystatuschangeblock:^ (afnetworkreachabilitystatus status) {

Switch (status) {

Case Afnetworkreachabilitystatusreachableviawwan:

Case Afnetworkreachabilitystatusreachableviawifi:

[Operationqueue Setsuspended:no];

Netstate = YES;

Break

Case Afnetworkreachabilitystatusnotreachable:

Netstate = NO;

Default

[Operationqueue Setsuspended:yes];

Break

}

}];

[Manager.reachabilitymanager startmonitoring];

return netstate;

}

/***************************************

In this case, if there's errorcode in DiC,

Call Errorblock (DIC)

No ErrorCode calls block (dic

******************************/

#pragma--mark Get Request method

+ (void) Netrequestgetwithrequesturl: (NSString *) requesturlstring

Withparameter: (nsdictionary *) parameter

Withreturnvaleublock: (returnvalueblock) block

Witherrorcodeblock: (Errorcodeblock) Errorblock

Withfailureblock: (Failureblock) Failureblock

{

Afhttprequestoperationmanager *manager = [[Afhttprequestoperationmanager alloc] init];

Afhttprequestoperation *op = [Manager get:requesturlstring parameters:parameter success:^ (afhttprequestoperation * operation, id responseobject) {

Nsdictionary *dic = [nsjsonserialization jsonobjectwithdata:responseobject options:nsjsonreadingallowfragments Error : nil];

Ddlog (@ "%@", DIC);

Block (DIC);

} failure:^ (Afhttprequestoperation *operation, Nserror *error) {

Failureblock ();

}];

Op.responseserializer = [Afhttpresponseserializer serializer];

[op start];

}

#pragma--mark POST request mode

+ (void) Netrequestpostwithrequesturl: (NSString *) requesturlstring

Withparameter: (nsdictionary *) parameter

Withreturnvaleublock: (returnvalueblock) block

Witherrorcodeblock: (Errorcodeblock) Errorblock

Withfailureblock: (Failureblock) Failureblock

{

Afhttprequestoperationmanager *manager = [[Afhttprequestoperationmanager alloc] init];

Afhttprequestoperation *op = [Manager post:requesturlstring parameters:parameter success:^ (AFHTTPRequestOperation * operation, id responseobject) {

Nsdictionary *dic = [nsjsonserialization jsonobjectwithdata:responseobject options:nsjsonreadingallowfragments Error : nil];

Ddlog (@ "%@", DIC);

Block (DIC);

/***************************************

In this case, if there's errorcode in DiC,

Call Errorblock (DIC)

No ErrorCode calls block (dic

******************************/

} failure:^ (Afhttprequestoperation *operation, Nserror *error) {

Failureblock ();

}];

Op.responseserializer = [Afhttpresponseserializer serializer];

[op start];

}

@end

3. Config: Create pch file, and Config.h file

PCH file introduces a common header file, as follows:

//

Prefixheader.pch

Mvvmtest

//

Created by Li Zeiru on 15/1/6.

Copyright (c) 2015 Li Zeiru. All rights reserved.

//

#ifndef mvvmtest_prefixheader_pch

#define MVVMTEST_PREFIXHEADER_PCH

#import "AFNetworking.h"

#import "Uikit+afnetworking.h"

#import "Config.h"

#import "NetRequestClass.h"

#import "SVProgressHUD.h"

#endif

Config.h is a variety of macro definitions and various enumeration types and block types, the code is as follows:

//

Config.h

Mvvmtest

//

Created by Li Zeiru on 15/1/6.

Copyright (c) 2015 Li Zeiru. All rights reserved.

//

#ifndef Mvvmtest_config_h

#define Mvvmtest_config_h

Defines the block type that returns the request data

typedef void (^returnvalueblock) (ID returnvalue);

typedef void (^errorcodeblock) (id errorCode);

typedef void (^failureblock) ();

typedef void (^networkblock) (BOOL netconnetstate);

#define Ddlog (XX, ...) NSLog (@ "%s (%d):" XX, __pretty_function__, __line__, # #__VA_ARGS__)

Accesstoken

#define Accesstoken @ "your own Access_token"

Request a network interface for public Weibo

#define REQUESTPUBLICURL @ "Https://api.weibo.com/2/statuses/public_timeline.json"

#define SOURCE @ "source"

#define TOKEN @ "Access_token"

#define COUNT @ "Count"

#define Statuses @ "statuses"

#define CREATETIME @ "Created_at"

#define WEIBOID @ "id"

#define WEIBOTEXT @ "text"

#define USER @ "user"

#define UID @ "id"

#define HEADIMAGEURL @ "Profile_image_url"

#define USERNAME @ "Screen_name"

#endif

4. Detailed resource file resource, structure such as:

Image in the storage of various pictures (3X,2X, etc.), interfacebuider inside is to put some xib and storyboard files, each responsible UI developer responsible for a storyboard

5. Detailed Model: The project is to request public microblogging interface we need to be on the page real user's avatar, user name, release date, blog, already implicit user ID and Weibo ID, file directory structure as follows:

The contents of the Publicmodel are as follows:

//

PublicModel.h

Mvvmtest

//

Created by Li Zeiru on 15/1/8.

Copyright (c) 2015 Li Zeiru. All rights reserved.

//

#import @interface Publicmodel:nsobject

@property (Strong, nonatomic) NSString *userid;

@property (Strong, nonatomic) NSString *weiboid;

@property (Strong, nonatomic) NSString *username;

@property (Strong, nonatomic) Nsurl *imageurl;

@property (Strong, nonatomic) NSString *date;

@property (Strong, nonatomic) NSString *text;

@end

6. detailed ViewModel layer, this layer is the most important layer, the following is the detail of this layer, Viewmodeclass is the parent class of all ViewMode, which stores the common part

The contents of the ViewModelClass.h are as follows:

//

ViewModelClass.h

Mvvmtest

//

Created by Li Zeiru on 15/1/8.

Copyright (c) 2015 Li Zeiru. All rights reserved.

//

#import @interface Viewmodelclass:nsobject

@property (Strong, nonatomic) Returnvalueblock Returnblock;

@property (Strong, nonatomic) Errorcodeblock Errorblock;

@property (Strong, nonatomic) Failureblock Failureblock;

Get the link status of a network

-(void) Networkstatewithnetconnectblock: (networkblock) Netconnectblock withurlstr: (NSString *) strURl;

Block blocks for incoming interactions

-(void) Setblockwithreturnblock: (Returnvalueblock) Returnblock

Witherrorblock: (Errorcodeblock) Errorblock

Withfailureblock: (Failureblock) Failureblock;

@end

The contents of the VIEWMODELCLASS.M are as follows:

//

Viewmodelclass.m

Mvvmtest

//

Created by Li Zeiru on 15/1/8.

Copyright (c) 2015 Li Zeiru. All rights reserved.

//

#import "ViewModelClass.h"

@implementation Viewmodelclass

#pragma get network reachable status

-(void) Networkstatewithnetconnectblock: (networkblock) Netconnectblock withurlstr: (NSString *) strURl;

{

BOOL netstate = [Netrequestclass Networkreachabilitywithurlstring:strurl];

Netconnectblock (netstate);

}

#pragma receive a block that passes through.

-(void) Setblockwithreturnblock: (Returnvalueblock) Returnblock

Witherrorblock: (Errorcodeblock) Errorblock

Withfailureblock: (Failureblock) Failureblock

{

_returnblock = Returnblock;

_errorblock = Errorblock;

_failureblock = Failureblock;

}

@end

The contents of the PublicWeiboViewModel.h are as follows:

//

PublicWeiboViewModel.h

Mvvmtest

//

Created by Li Zeiru on 15/1/8.

Copyright (c) 2015 Li Zeiru. All rights reserved.

//

#import "ViewModelClass.h"

#import "PublicModel.h"

@interface Publicweiboviewmodel:viewmodelclass

Get a list of tube scarves

-(void) Fetchpublicweibo;

Jump to Weibo details page

-(void) Weibodetailwithpublicmodel: (Publicmodel *) Publicmodel Withviewcontroller: (Uiviewcontroller *) Supercontroller;

@end

The contents of the PUBLICWEIBOVIEWMODEL.M are as follows:

//

publicweiboviewmodel.m

Mvvmtest

//

Created by Li Zeiru on 15/1/8.

Copyright (c) 2015 Li Zeiru. All rights reserved.

//

#import "PublicWeiboViewModel.h"

#import "PublicDetailViewController.h"

@implementation Publicweiboviewmodel

Get a public Weibo

-(void) Fetchpublicweibo

{

Nsdictionary *parameter = @{token:accesstoken,

COUNT: @ "100"

};

[Netrequestclass netrequestgetwithrequesturl:requestpublicurl withparameter:parameter WithReturnValeuBlock:^ (ID returnvalue) {

Ddlog (@ "%@", returnvalue);

[Self fetchvaluesuccesswithdic:returnvalue];

} witherrorcodeblock:^ (id errorCode) {

Ddlog (@ "%@", ErrorCode);

[Self errorcodewithdic:errorcode];

} withfailureblock:^{

[Self netfailure];

Ddlog (@ "Network exception");

}];

}

#pragma get the right data to handle the right data

-(void) Fetchvaluesuccesswithdic: (Nsdictionary *) returnvalue

{

The data obtained from the background is processed and then passed to the Viewcontroller layer for display

Nsarray *statuses = returnvalue[statuses];

Nsmutablearray *publicmodelarray = [[Nsmutablearray alloc] initWithCapacity:statuses.count];

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

Publicmodel *publicmodel = [[Publicmodel alloc] init];

Set the time

NSDateFormatter *iosdateformater=[[nsdateformatter Alloc]init];

[Email protected] "EEE MMM D HH:mm:ss Z yyyy";

Must be set, otherwise cannot be resolved

Iosdateformater.locale=[[nslocale alloc]initwithlocaleidentifier:@ "en_US"];

NSDate *date=[iosdateformater Datefromstring:statuses[i][createtime]];

Destination format

NSDateFormatter *resultformatter=[[nsdateformatter Alloc]init];

[Resultformatter setdateformat:@ "MM month DD day hh:mm"];

Publicmodel.date = [Resultformatter stringfromdate:date];

Publicmodel.username = Statuses[i][user][username];

Publicmodel.text = Statuses[i][weibotext];

Publicmodel.imageurl = [Nsurl Urlwithstring:statuses[i][user][headimageurl]];

Publicmodel.userid = Statuses[i][user][uid];

Publicmodel.weiboid = statuses[i][weiboid];

[Publicmodelarray Addobject:publicmodel];

}

Self.returnblock (Publicmodelarray);

}

#pragma processing the ErrorCode

-(void) Errorcodewithdic: (Nsdictionary *) errordic

{

Self.errorblock (Errordic);

}

#pragma handling of network anomalies

-(void) netfailure

{

Self.failureblock ();

}

#pragma jump to the details page, if you require a network request, you can add the appropriate Web request in this method

-(void) Weibodetailwithpublicmodel: (Publicmodel *) Publicmodel Withviewcontroller: (Uiviewcontroller *) Supercontroller

{

Ddlog (@ "%@,%@,%@", Publicmodel.userid,publicmodel.weiboid,publicmodel.text);

Uistoryboard *storyboard = [Uistoryboard storyboardwithname:@ "Main" Bundle:[nsbundle Mainbundle]];

Publicdetailviewcontroller *detailcontroller = [Storyboard instantiateviewcontrollerwithidentifier:@] Publicdetailviewcontroller "];

Detailcontroller.publicmodel = Publicmodel;

[Supercontroller.navigationcontroller Pushviewcontroller:detailcontroller Animated:yes];

}

@end

7.The directory structure of the Viewcontroller layer is as follows:

The above code will not stick to each other (the main hand by command + C Press tired), the following links will have the source code

8.The structure in Storybord is as follows:

The final effect of the run:

9. The complete directory structure, the business logic between the pages, and the request data of the network are placed in the ViewModel layer, of course, this is not absolute, to be flexible grasp. I personally like programming, because the programming flexibility will be very fun.

The article is almost over, here is a summary of the use of SVN high-frequency and more important commands it (of course, I usually mainly use Xcode with the SVN visual management ~)

(1), update Local Code command

SVN up update version

SVN Info View current version information

(2), the code of the submission

SVN info View current local version information

SVN up update to latest version information

SVN St View file status m-Modify D-delete A-add U-Update?-Unknown status-warning C-conflict

SVN add FileName: What if it appears? Generally is the problem when adding files, after the file svn add filename, the status of the file will be changed to a

SVN del fileName: if it appears! This is usually a warning when you delete a file. After executing the SVN del filename command, the file's status is changed to D

SVN ci-m "Reason for submission"

Green Jade Desk
Source: http://www.cnblogs.com/ludashi/

iOS Development > Learning-Talk about MVVM's architecture design and team collaboration

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.