Updated date:

MVVM An Improvement to MVC In iOS

Author:

Keen interest in finding different solutions to a problem. Currently exploring different architectures for iOS applications.

mvvm-an-improvement-to-mvc-in-ios

A Quick Recap

In previous article “Model View Controller in iOS” I have tried to explain, why do we even need these patterns like MVC, MVVM etc. We have also explored MVC and looked into the pros and cons MVC comes with.

In MVC, we separate our View from Model by introducing a Controller that binds them together. This separation provides better code maintenance and testability. But in iOS version of MVC we have a limitation that View and Controller are tightly coupled thus it’s difficult to mock view in order to test the Controller. As the complexity of View increases, the Controller becomes bulky and becomes harder to test.

What is MVVM (Model View ViewModel)

MVVM initially introduced by the Microsoft’s John Gossman used in Windows Presentation Foundation (WPF). Like MVC, MVVM also provides a Glue known as ViewModel that binds the View and Model together.

View is the visible entity on screen that user can interact with. It displays information to user and allow user to add/update information or perform any actions like change user name or perform save action. Where as Model provides all the data and provides operations that a View can perform. Let's dive into the real app to see the working of Glue.

Consider you are developing a Temperature app that allows user to see temperature of his/her city and user can also change city temperature as well. App will look something like this:

mvvm-an-improvement-to-mvc-in-ios

When user opens up the app this is what happens to show temperature on the view:

mvvm-an-improvement-to-mvc-in-ios

In the above case, onViewDidLoad gets triggered, glue will get the information from the Model by calling getTemperature function. This function will return the temperature in Int type, so Glue has to format this value before we can display it. So glue will call its helper function ConvertInDisplayForm. This function takes temperature and returns a String in “<Temp> °C” format. Then glue will set the formatted value into Label by calling setTempLabelText. Our app will now show temperature of “20 °C” on the screen.

Now lets see what will happen when user will update temperature to 30 °C:

mvvm-an-improvement-to-mvc-in-ios

In this case, save function is triggered by the View, Glue gets the entered text, converts it into Int value and then call setTemperature of Model. It also formats the new temperature and updates the UI with new temperature.

Lets list the tasks of the Glue:

  • It fetches data from the Model.
  • It converts the data to viewable form like “20 °C”.
  • It listens to user action to perform respective operation in Model.
  • It get data from the View and prepare it to pass it to the Model.
  • It updates the information shown on UI.

Now you will be thinking, Glue is the Controller? Yeah in MVC, it is. So, in MVVM is ViewModel is Glue?

MVVM divides the Glue in two concerns:

  1. ViewModel
  2. Bindings
mvvm-an-improvement-to-mvc-in-ios

ViewModel provides all the data properties that View requires and state of UI. It also provides commands (event handlers or operations) that View can initiate. Where as Bindings will update information on UI when model changes (or vise versa). It also binds UI events like Button Tap with commands provided by the ViewModel.

Microsoft Windows Presentation Foundation provides Binding framework that is used to bind UI elements to the ViewModel. In iOS we can use UIViewController class to bind elements to the ViewModel class.

Temperature App in MVVM:

protocol TemperatureViewModelDelegate {
	func temperatureUpdated(_ vm: TemperatureViewModel)
}
class TemperatureViewModel {

	private var _temperature: Int = 0
	public var delegate: TemperatureViewModelDelegate?
	public var temperature: String {
		return "\(_temperature) °C"
	}

	public func loadTemperature() {

		_temperature  = 20
		delegate?.temperatureUpdated(self)
	}

	public func changeTemperature(to newTemperature: String) {

		_temperature = Int(newTemperature) ?? 0
		delegate?.temperatureUpdated(self)
	}
}

class TemperatureViewController : UIViewController, TemperatureViewModelDelegate  {

	@IBOutlet weak var tempLbl: UILabel!
	@IBOutlet weak var tempTxt: UITextField!
	var vm = TemperatureViewModel()
	
	func viewDidLoad() {
		super.viewDidLoad()

		vm.delegate = self
		vm.loadTemperature()
	}

	func temperatureUpdated(_ vm: TemperatureViewModel) {
		self.tempLbl.text = vm.temperature
	}

	@IBAction func updateTemperature() {

		vm.changeTemperature(to: tempTxt.text!)
	}
}

As you can see, controller is only binding the data to and from ViewModel and pass operation events to ViewModel. ViewModel is implementing all the logic of loading data and maintaining the state of UI.

Will the ViewModel gets bulky as Controller in MVC? We can divide the ViewModel into sub ViewModels that handle specific type of Views. For example, Home screen displays list of food items. In this situation you can create ListFoodItemViewModel that represents List Food Item screen then use it in HomeViewModel.

How MVVM Improves MVC

In MVC, controller is the Glue that has lots of responsibilities (as discussed above) making the controller bulky and as iOS controller is tightly coupled with View, it was hard to test it as well. But MVVM move the state of UI and communication with the model to ViewModel, it is lot easy to test UI states in different scenarios. In addition to that ViewModels can break into sub ViewModels that reduces the size and complexity of ViewModel.

MVVM Pros and Cons

  • Provide weak coupling between View, View state and Model.
  • Allows greater testability of view states
  • Allows better maintenance of complex view.
  • Overhead of writing binding code.
  • Make implementation of simple screen, complex.
  • Increase development and maintenance cost of simple application.

Conclusion

MVVM breaks the responsibilities into more refined form than MVC which improves unit testing and maintenance of the complex view but it increase the code development and maintenance cost. It’s not necessary to use either MVVM or MVC into you code. You can mix match them and use MVVM for complex views and MVC for simple views in a single application. This can help you reduce unnecessary development and maintenance cost.

You can find Temperature App implementation using MVVM here. If you have any question, comments or suggestion, feel free to drop a comment.

© 2020 BAG

Comments

miamifishingpros from USA on February 14, 2020:

Nice

Related Articles