Model View View-Model
In the previous section, we have discussed the MVC design pattern, which is simple to understand and easier to use. However, the MVC has some disadvantages, which lead to the evolvement of a new design pattern that is Model View View-Model. In this section of the tutorial, we will discuss the components of MVVM in detail. We will also look at the limitations of the Model View Controller design pattern.
What is MVVM?
MVVM (Model View View-Model) is an iOS architectural design pattern in which we separate objects into three main components.
The MVVM adds a new component ViewModel into the MVC design pattern so that the role of the view controller can be minimized, and the business logic can take place at ViewModel.
Problems with MVC
The most common problem with the MVC is data formatting. In MVC, the model contains the application's data. While developing iOS applications, there are the requirements that the data needs to be formatted before presenting it to the user.
Suppose, in an iOS application, there is a need to display the date to the user, which is returned by the server. However, if the server returns a date into a long milliseconds format and we display the exact date to the user that is returned by the server, then how the user will be going to understand the date format. Hence, there is a need to format this date into the string using date formatter.
In MVC, the problem is where the formatting takes place. The model is not required to be told about the data being displayed to the user. The model doesn't need to understand the data displayed to the user; therefore, the only object that can be used to place the formatting code is Controller since the controller is already heavy after having so much business logic, including the data source and delegate method. Hence, the controller becomes so much heavy in MVC because all the data manipulation tasks also take place at the Controller.
Where to use MVVM
The MVVM Provides a solution to the problem of a heavy controller in MVC. It adds a fourth component into the scheme that is ViewModel. The ViewModel is responsible for managing the data manipulation tasks, and it also manages the model by transmitting the model's data to the view via a view controller. This pattern can be used where we need to transform models into another representation for a view. For example, we can use the view model for transforming a date object into a formatted string, a decimal value into a formatted currency string, etc. This pattern compliments MVC well. The purpose is to minimize the role of a view controller by adding another component. However, the view controller still performs some major handling, including outlets and injecting the formatted data into the outlets.
The MVVM Project Architecture
The following image defines the architecture of an XCode project that is following MVVM as a design pattern.