MVVM An Improvement to MVC In iOS

Updated on February 4, 2020
Bagexito profile image

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

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:

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

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:

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

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.

Questions & Answers

    © 2020 BAG

    Comments

      0 of 8192 characters used
      Post Comment
      • miamifishingpros profile image

        miamifishingpros 

        7 weeks ago from USA

        Nice

      working

      This website uses cookies

      As a user in the EEA, your approval is needed on a few things. To provide a better website experience, turbofuture.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

      For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

      Show Details
      Necessary
      HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
      LoginThis is necessary to sign in to the HubPages Service.
      Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
      AkismetThis is used to detect comment spam. (Privacy Policy)
      HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
      HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
      Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
      CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
      Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
      Features
      Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
      Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
      Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
      Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
      Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
      VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
      PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
      Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
      MavenThis supports the Maven widget and search functionality. (Privacy Policy)
      Marketing
      Google AdSenseThis is an ad network. (Privacy Policy)
      Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
      Index ExchangeThis is an ad network. (Privacy Policy)
      SovrnThis is an ad network. (Privacy Policy)
      Facebook AdsThis is an ad network. (Privacy Policy)
      Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
      AppNexusThis is an ad network. (Privacy Policy)
      OpenxThis is an ad network. (Privacy Policy)
      Rubicon ProjectThis is an ad network. (Privacy Policy)
      TripleLiftThis is an ad network. (Privacy Policy)
      Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
      Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
      Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
      Statistics
      Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
      ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
      Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
      ClickscoThis is a data management platform studying reader behavior (Privacy Policy)