MVVM is an abbreviation of Model View ViewModel. A Model-View-ViewModel is software architectural pattern that was created way back in 2005 by John Gossman. MVVM is quite similar to MVC, but it provides better connect of the UI and business sense than that of MVC. In MVVM pattern, each view on the screen will be backed by a view model and it represents the data for the view.
2. MVVM flow Layout & Theoretical Background:
In an MVC-based project, View is Connecting with its ViewController. ViewController is easily overloaded and increases its size when the application becomes bigger. So ViewController is affected in MVC. This drawback Solution in MVVM pattern.
MVVM Data flow shown in Below Fig 1.
As per above figure, the three core components of MVVM model respectively are,
1. As per above figure, the three core components of MVVM model respectively are,
2. Model: it is class that holds our App Data.
3. View/ViewController: it presents our View and ViewController Class.
4. ViewModel: ViewModel binds the Model and ViewController, it’s the heart of MVVM design pattern. It provides the connection between the model class and the view/view controller. View Model is capable of observing changes in Model and synchronize itself with the events.
Let’s start Understanding MVVM Design pattern with a simple example.
First, create a project in Xcode. Also, create Model and ViewModel Class. In this project, we have taken tableView and shown employee name and its department using MVVM design pattern.
Shown model class in below Fig 2. In model class, we have defined variable and function, as per our requirement.
– In View-Model Class we have taken a Model object, so we have used – Model class property in View- Model Class. In our project model Employee is a model object.
– Here Model and View-Model class are connecting to each other.
– Shown View-Model Class in Fig. 3
– First, take View-Model object in ViewController Class. myViewModel is View-Model object. In our project, we have taken table view.
– In this class, View-Model and View-Controller are connecting to each other. View-model object through, we get all data of View-Model class as per requirement.
– View (Controller) class shown in Fig. 4.
Also shown Output in fig. 5
– Code reuse: In View-Model class we implement init, setup and view presentation method, so we use this functionality in each new view controller.
– Improved Testability: In MVVM we can make all classes separate so we can easily find an error.
– Reduce code size
– MVVM pattern not useful for single View application, when we work on Multiple views then it is useful.
MVC and MVVM both patterns are useful for iOS app development. MVVM is new Concept for the design pattern. MVVM is more useful when app size is bigger because the separation of Model, View and View-Model class can reduce complexity.