---
title: "#126: Simpler View Controllers with View Models 🤓"
url: https://littlebitesofcocoa.com/126-simpler-view-controllers-with-view-models
author: Jake Marsh
published: 2015-11-16
topics: ["Techniques"]
description: "In our ongoing quest to build better apps, it's important for us to keep up as new techniques and best practices emerge."
---

# #126: Simpler View Controllers with View Models 🤓

By Jake Marsh, November 16, 2015. HTML: https://littlebitesofcocoa.com/126-simpler-view-controllers-with-view-models

In our ongoing quest to build better apps, it's important for us to keep up as new techniques and best practices emerge. One such technique that's recently been growing in popularity is the use of _View Models._ Today we'll look at how they fit into an app, and why we'd use them.

Traditionally, we'd use the <i>Model View Controller</i> technique to build our apps. Sounds great, but on iOS it usually ends up looking something like this:

<img src='https://media.littlebitesofcocoa.com/bite-assets/126-mvc-diagram.png' style='max-width: 354px;' />

This approach can often lead to <i>gigantic</i> **UIViewController** subclasses, with <i>long</i> lists of responsibilities: networking/data loading code, table/collection view delegate methods, UI interaction, UI layout, and so on.

That's where the <i>Model View View Model</i> approach comes in. Don't be fooled by the name, we still need **view controllers**. When applied on iOS, MVVM ends up looking something like this:

<img src='https://media.littlebitesofcocoa.com/bite-assets/126-mvvm-diagram.png' style='max-width: 403px;' />

We'll add a new _view model_ type in between our **model** and **view controller**. Our _view model_ will take over loading data, as well transforming/processing that data. Then it will expose that transformed data as <i>read-only</i> **properties**.

``` swift
struct SpaceshipViewModel {
  private var ship: Spaceship

  let displayName: String { "\(ship.squadron): \(ship.name)" }
  func loadShips(start: Int = 0) { ... }
}
```

With our new _View Model_, we now have a clear place to put things like networking, data persistence, and all our business logic. Our **view controllers** can now relax a bit and handle things like user input and size class changes. Next time, we'll look at how we can make our **view controller** automatically react to changes in the _view model_.

**Author's Note:** Interested in learning more about this? [This introduction](http://www.sprynthesis.com/2014/12/06/reactivecocoa-mvvm-introduction/) from [Bob Spryn](http://twitter.com/sprynmr) is fantastic. It covers everything from start to finish and does a great job explaining both the "why" and "how" along the way. Highly recommended reading.
