Implementing View Models

The basic idea of the view model is to take the data from the model and then provide the data to the view.

Let’s check out the implementation of the OrderViewModel which is responsible for displaying order-related data on the screen.

The OrderViewModel is a plain view model, which simply returns the data as a primitive type to the view. Since it does not return a complex object, the data can be easily displayed on the view.

View models can either be smart or plain.

Smart view models can have logic to make Webservice calls through the web service layer.

calls through the web service layer. A view model is said to be plain when it simply provides data to the view and does not perform any complex operation.

The OrderViewModel represents each order, which will be displayed in a UITableView control.

Although you can simply use an array of OrderViewModels and populate your UITableView , I recommend creating a parent view model that represents the entire view.

This way, you will always have the flexibility to provide data for additional view items like SegmentedControl , PickerView , etc.

The parent view model in our app is called OrderListViewModel . The OrderListViewModel represents the entire screen which is responsible for displaying orders.

The second view model we will implement is called the AddCoffeeOrderViewModel . This view model is responsible for providing data as well as gathering input data from the Add Coffee Order screen.

If you look at the coffee ordering screen below, you will realize that the coffee ordering screen requires a couple of different things before we can order coffee.

Luckily, all this information can be provided to the view by AddCoffeeOrderViewModel .

One thing to notice is the types and sizes properties of the AddCoffeeOrderViewModel .