preface

In line with the avenue to simple, from shallow to deep ideas. This article will start with a simple example and walk through the application of MVVM in iOS. Say a view, compare pros and cons, if have the place of inadequacy, still hope each big god points out patiently, junior generation is very grateful!

The article directories
  • The battle for architecture
  • The MVVM que
  • The engineering practice
  • conclusion

First, the debate over architecture

Apple’s official recommendation for MVC is as follows:

View
Model
Controller
Model
View
Controller
View
Model
Model
Data manager
View
Data presenter
Controller
Data processor

Whereas in Controller in iOS because of apple’s built-in View lifecycle, viewDidLoad and so on, there’s been some debate about MVC architecture in iOS, some people think there’s no View or Controller in iOS development, Only the Model + ViewController; Personally, I prefer the division of Casa Taloyum:

What M should do: 1. Provide data to ViewController 2. Provide interface for ViewController to store data 3. Provide abstract basic business components for Controller to schedule what C should do: 1. Manage the View Container lifecycle. 2. Generate all View instances and put them into View Container 3. Listen for business related events from the View and work with Model to complete business for the corresponding events. V should do: 1. Respond to non-business related events and animate them, click on feedback (if appropriate, try to put it in View), etc. 2. Interface element expressionCopy the code

Strictly speaking, Controller does do view-related operations, but this is a view container encapsulated by Apple for developers, exposing some template methods for easy call. We should develop iOS MVC architecture on this basis 😝 (PS: personal opinion, just talking); MVVM, which evolved from MVC, has been further optimized:

ViewModel
Controller
ReactiveCocoa and MVVM, introduction

At this point, I think you have some basic understanding of MVC and MVVM, and you can use your own architecture to really implement your chosen architecture.


To summarize the comparison result: MVC

Advantages: Common architecture; Processing of high coupling degree of logic convenience; Disadvantages: high coupling degree; Poor reusability; Poor test performance;

MVVM

Advantages: low coupling degree; High reusability; High testability; Clearer hierarchy; Low reconstruction cost; Disadvantages: processing the logic of high coupling degree is more complex; If you join RAC, the cost of learning will increase; Some bugs are difficult to debug;

2. MVVM

The author chooses the RAC implement MVVM architecture, of course not necessary and important implementation architecture, used in some libraries are tools, also can use KVO implementation, native KVO implementation will encounter in the process of using KVO traps that some iOS, and such as the parent class is covered by subclasses KVO method, the judgment of the news from your listening too lengthy, etc. I recommend using Facebook’s open source KVOController framework, which is similar to the example, so I won’t repeat the examples;

Ok, 👇 start to write the code below ~ the project structure is as follows:

2.1 ZBMVVMSimpleViewController

Coordinate viewModel binding model, view binding viewModel;

- (void)viewDidLoad { [super viewDidLoad]; // Initialize self.simplemodel.name = @"ShuaiBin"; / / create a view [self view addSubview: self. SimpleView]; // /viewModel binding model [self.simpleViewModelbindModel:self.simpleModel]; // View binding viewModel [self.simpleViewbindViewModel:self.simpleViewModel];   
}
Copy the code

2.2 ZBMVVMSimpleView

Create a view to bind the internal logic of the viewModel;

- (instancetype)init
{
    self = [super init];
    if(self){ self.frame = [UIScreen mainScreen].bounds; self.backgroundColor = [UIColor whiteColor]; self.nameButton = [UIButton buttonWithType:UIButtonTypeSystem]; _nameButton.frame = CGRectMake(0, 0, 100, 50); _namebutton. center = CGPointMake(self.frame.size. Width / 2.0, (self.frame.size. Height / 3.0 * 1)); _nameButton.backgroundColor = [UIColor blackColor]; [_nameButtonsetTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_nameButton addTarget:self action:@selector(nameButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_nameButton];
    }
    returnself; } // Button click method - (void)nameButtonAction {if(self.viewModel){ [self.viewModel changeButtonTextAction]; }} // bind viewModel - (void)bindViewModel:(id)viewModel
{
    self.viewModel = viewModel;
    @weakify(self);
    [[RACObserve(self.viewModel, nameStr) ignore:nil] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self.nameButton setTitle:x forState:UIControlStateNormal];
    }];
}
Copy the code

2.3 ZBMVVMSimpleViewModel

The zBMvVMSimpleViewModel.h section: exposes some callable interfaces:

@interface ZBMVVMSimpleViewModel : NSObject @property (nonatomic, strong) NSString *nameStr; // bind model - (void)bindModel:(id)model; - (void)changeButtonTextAction; @endCopy the code

Zbmvvmsimpleviewmodel. m: Implement binding model, button change name;

@interface ZBMVVMSimpleViewModel() @property (nonatomic, strong) ZBMVVMSimpleModel *model; @property (nonatomic, assign) BOOL isClick; Implementation simpleViewModel - (void)bindModel:(id)model { self.model = model; self.nameStr = self.model.name; } - (void)changeButtonTextAction {_isClick =! _isClick;if(_isClick){
       self.model.name = @"Jade of Fire";
    }else{
       self.model.name = @"ShuaiBin";
    }
    self.nameStr = self.model.name;
}

@end
Copy the code

From this simple example, you can see how the various parts of MVVM relate to each other and how this architecture is implemented;

The MVVM Model does not interact with the View; the interaction moves to the ViewModel; The View holds the ViewModel, the ViewModel holds the Model, and vice versa. The View is easily coupled directly to the Model, which loses the meaning of the architecture.

To summarize:

The core of MVVM is :(personal opinion) 1. Bidirectional binding of MVVM; 2. Decoupled Model and View;

Engineering practice

Reference iOS MVVM+RAC from the framework to actual combat myself to achieve a small demo:

After reading some implementation cases on the Internet, I finally chose this kind of engineering mode with clear structure and convenient management. By the way, I tell the author that I have “liked” and “star”.

The dataSource parent class of the tableView is mVVM-based, which is used to quickly set up the Settings page, the personal information page framework, which is also quite interesting.

I would like to mention a small problem that I find in the post block: weak.

- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block { self.translatesAutoresizingMaskIntoConstraints =  NO; MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; block(constraintMaker);return [constraintMaker install];
}
Copy the code

It can be seen from the source code that the block of navigation is a local variable, which will be released after the method call. There is no mutual holding, so weak can be used.

conclusion

The MVVM pattern has been a hot topic and has been imitated in many languages. Although the View and Model separated, but also added some data binding, data separation code. In short, there are pros and cons, for developers to choose freely. ViewController can be slimmed down in more than one mode. In the actual development process, the engineering mode may have been fixed, which requires step by step code optimization, and it is really difficult to switch to MVVM all at once. Tang Qiao in the misunderstood MVC and the deified MVVM provides several ViewController slimming ideas, worth learning from.

Well, that’s all for MVVM this time, and more in-depth and interesting content will be shared in the future. Welcome to discuss ~

Finally, attached is the project link:

Click here to download

Blog recommendation:

IOS application architecture on view layer organization and call scheme

Getting started with ReactiveCocoa and MVVM

Misunderstood MVC and deified MVVM

IOS MVVM+RAC from framework to combat

Ape question bank iOS client architecture design

The MVVM exotic flower said