MVVM (Model-View-ViewModel) is another design pattern that people used in mobile development, including on iOS. This pattern gains popularity amongs mobile developer since the “C” layer from MVC handle so many things. Some people jokes about Massive-View-Controller (MVC) because the ViewController not really a controller, it also handle the UI, networking, and others.
MVVM provides good separation responsibility to it. The Model and the View are still the same. The ViewModel layer handle some logic like UI logic, bussiness logic, communicate to database or network service, so the main act in this pattern is the ViewModel. In other word, the ViewModel is the middle man between the View and the Model. Since the Controller is a UIViewController (not pure controller), people believe it is a View, not the Controller. I will show you how this pattern applied in a simple networking project using Alamofire and SDWebImage.
This is how my project grouping folder in MVVM design pattern.
MVVM in this project containts some different layer and its own responsibility, the Model, View, ViewModel, and Service.
The view represent how the data will rendered to the view. The storyboard file for this case is responsible for this layer. Here, I create simple view that holds UIImageView and two UILabel to show it to the user. Also, hook up it to the ViewController so we can interact with the view components via code. the ViewController.swift file is also a View, just ignore the Controller word.
For this example, I use Service rather than Store, since I’m just communicating to the network. This class is responsible to make a network call and give the result to the controller.
Like I said earlier, the ViewModel is the middle man between the View and the Model. it makes request to the DataService layer, formatting data and represent it to the View layer (Controller), hold the loading state, and other. To make it easy, it’s just the Model for the View. The public properties and public closures are used by the ViewController to listen to any changes in the ViewModel, just like the delegate pattern in iOS.
Controller / ViewController
Like I said earlier, the ViewController or Controller belongs to the View layer. the code shoud like this.
The ViewController (View) communicates to the ViewModel, and listen to it using closures.
Build and run and you should see the data that you requested.
You can see my full code here.
MVVM is a better design pattern to avoid Massive View Controller, since the UI logic, networking / database and formatting the data done in the ViewModel layer. It is also make easier to test, rather than the MVC pattern. This pattern got many attention from the developer. If you still use MVC it is a big project, I think it is time to adopt to this pattern, MVVM.