As we are familiar with MVC design pattern and it is one of the standard approach to build iOS Applications. MVVM is very similar to MVC. It formalizes the tightly coupled nature of the view and controller and introduces a new component
Under MVVM, the view and view controller become formally connected and we treat them as one. Views still don’t have references to the model, but neither do controllers. Instead, they reference the view model.
view-model is an excellent place to put validation logic for user input, presentation logic for the view, network requests, and other miscellaneous code. The one thing that does not belong in the view model is any reference to the view itself. The logic in the view model should be just as applicable on iOS as it is on OS X. In other words, we should not import
UIKit.h in your view-models.
iOS apps written using MVVM are highly testable, since the view model contains all the presentation logic and doesn’t reference the view, it can be fully tested programmatically.
The motivation behind MVVM on iOS, for me is that it reduces the complexity of one’s view controllers and makes one’s presentation logic easier to test. We’ll see how it accomplishes these goals with example.
MVVM is basically just a spruced-up version of MVC, so it’s easy to incorporated into an existing app with a typical MVC architecture. Let’s take a simple
Person model and corresponding view controller:
Now let’s say that we have a
viewDidLoad, just sets some labels based on its model property:
Now let’s see how we can augment this with a
Our view model’s implementation would look like the following:
We’ve moved the presentation logic in
viewDidLoad into our view model. Our new
viewDidLoad method is now very lightweight:
So, as we can see, not a lot changed from our MVC architecture. It’s the same code, just moved around. It’s compatible with MVC, leads to lighter view controllers, and is more testable.