IOS--MVVM design mode

Source: Internet
Author: User

First, the typical iOS architecture--mvc

 

In a typical MVC setup, model renders the data, the VIE renders the user interface, and Viewcontroller adjusts the interaction between the two.

Although the view and view controllers are technically different components, they are always hand in hand, paired, view cannot match different view controllers, and vice versa. The relationship between view and view controller is as follows:

In a typical MVC application, many logic is placed in the Viewcontroller. Some of them really belong to the view Controller, but more of the "Presentation logic" (presentation logic), which is the thing that transforms the model data into what the view can render, For example, convert a nsdata to a formatted nsstring. The typical MVC design pattern does not do much to solve the problem of an increasingly heavy-weight view controller in iOS apps.

Second, the enhanced version of MVC--MVVM 

Add a view Model to MVC and put all the presentation logic in it, between the Model and the view controller, as shown in:

In MVVM, you formally link the View and the Controller (view controller) and move the presentation logic from Viewcontroller to a new object, the view Model.

The advantages of MVVM:

* Reduce the complexity of viewcontroller and make the presentation logic easier to test;

* Can be compatible with MVC architecture;

* Increase the testability of the application;

* Works best with a binding mechanism.

MVVM is basically an improved version of MVC, so it's easy to integrate into existing applications that use a typical MVC architecture.

Let's look at a simple person model and the corresponding view Controller:

#import <Foundation/Foundation.h>@interface  person:nsobject@property (nonatomic, readonly) NSString *salutation; @property (nonatomic,readonly) NSString *FirstName; @property (Nonatomic,  readonly) NSString *LastName; @property (nonatomic,readonly) nsdate *birthDate; -(Instancetype) Initwithsalutation: (NSString *) Salutation FirstName: (NSString *) FirstName LastName: (NSString *) LastName BirthDate: (NSDate *) birthDate; @end

Here's a personviewcontroller, in Viewdidload, just set some labels based on his model property:

-(void) viewdidload{[Super Viewdidload]; if(Self.moedl.salutation.length >0) {Self.nameLabel.text= [NSString stringWithFormat:@"%@.%@.%@", Self.moedl.salutation,self.moedl.firstname,self.moedl.lastname]; }    Else{Self.nameLabel.text= [NSString stringWithFormat:@"%@.%@", Self.moedl.firstname,self.moedl.lastname]; } NSDateFormatter*dateformatter =[[NSDateFormatter alloc]init]; [Dateformatter Setdateformat:@"eeee MMMM d,yyyy"]; Self.birthdateLabel.text=[Dateformatter stringFromDate:self.moedl.birthDate];}

  

It all went straight to the typical MVC. Now let's look at how to use a viewmodel to enhance it and create a Personviewmodel:

PersonViewModel.h

#import <Foundation/Foundation.h>#import"Person.h"@ Interface  personviewmodel:nsobject@property (nonatomic,readonly) person *person;@ Property (nonatomic,readonly) NSString *nametext; @property (nonatomic,readonly ) NSString *Birthdatetext; -(Instancetype) Initwithperson: (person *) person; @end

personviewmodel.m

-(Instancetype) Initwithperson: (Person *) person{ Self=[Super Init]; if(!Self ) {        returnNil; } _person=Person ; if(Person.salutation.length >0) {_nametext= [NSString stringWithFormat:@"%@.%@.%@", Self.person.salutation,self.person.firstname,self.person.lastname]; }    Else{_nametext= [NSString stringWithFormat:@"%@.%@", Self.person.firstname,self.person.lastname]; } NSDateFormatter*dateformatter =[[NSDateFormatter alloc]init]; [Dateformatter Setdateformat:@"eeee MMMM d,yyyy"]; _birthdatetext=[Dateformatter stringFromDate:person.birthDate]; returnSelf ;}

This adds the representation logic in the Viewdidload to the ViewModel. At this point, the new viewdidload will be very lightweight:

-(void) viewdidload{  [Super Viewdidload];   = Self.viewModel.nameText;   = self.viewModel.birthdatetext;          }

So we're not making too many changes to the MVC architecture. Or the same code, just moved the location. It is compatible with MVC, resulting in more lightweight viewcontrollers.

In MVVM, we try to move the code as much as possible into the view model. It's much easier to test viewcontroller because they don't do a lot of things, and the view model is very easy to test. Now look at the following code:

Specbegin (person) nsstring*salutation =@"Dr."; NSString*firstname =@" First"; NSString*lastname =@" Last"; NSDate*birthdate = [NSDate dateWithTimeIntervalSince1970:0]; It (@"should use the salutation available.", ^{ person*person =[[Person alloc] initwithsalutation:salutation firstname:firstname lastname:lastname birthdate:birthdate]; Personviewmodel*viewmodel =[[Personviewmodel alloc] Initwithperson:person]; Expect (Viewmodel.nametext). To.equal (@"Dr First Last");    }); It (@"Should is not a unavailable salutation.", ^{ person*person =[[Person alloc] Initwithsalutation:nil firstname:firstname lastname:lastname birthdate:birthdate]; Personviewmodel*viewmodel =[[Personviewmodel alloc] Initwithperson:person]; Expect (Viewmodel.nametext). To.equal (@" First Last");    }); It (@"should use the correct date format.", ^{ person*person =[[Person alloc] Initwithsalutation:nil firstname:firstname lastname:lastname birthdate:birthdate]; Personviewmodel*viewmodel =[[Personviewmodel alloc] Initwithperson:person]; Expect (Viewmodel.birthdatetext). To.equal (@"Thursday January 1, 1970"); }); Specend

If this logic is not moved into the view Model, we will have to instantiate a full view controller and the accompanying view and then compare the label values in the view. Not only does this become an indirect layer of trouble, but it only represents a very vulnerable test. Now, you can freely modify the view hierarchy as you wish without worrying about breaking unit tests. The benefits of using MVVM for testing are obvious.

Note that in this simple example, the model is immutable, so you can specify the properties of the view model only at initialization time. For variable model, some binding mechanisms are also needed so that the view model can update its properties when the model changes behind it. This is, once the model on the view model has changed, the view's properties also need to be updated. The model changes should cascade down through the view model into view.

On OS X, you can use cocoa bindings, but there is no such good configuration available on iOS. However, KVO provides the possibility to implement on iOS.

IOS--MVVM design mode

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.