iOS: Avoiding MVC (Massive View Controller) For UITableViewController

Nathan Hunston
Mobile Engineering
Published in
2 min readNov 22, 2014

--

iOS is a great platform there is however one thing that bugs me about it. Apple say that iOS follows the MVC design pattern but when it comes to ViewControllers it just….doesn’t. Views and Controllers are combined into a ViewController leading to bloat and hard to test code. This leads to the other MVC, Massive View Controller.

How Can This Be Avoided

So lets assume you want a UITableView which is going to show a series of rows, maybe it looks something like this:

Now an iOS engineer with any experience will tell you that this is pretty easy to get setup. Create a UITableViewController and set it up in the Storyboard, easy.

The problem with this is when it comes to adding any form of logic to the UITableView. Normal UITableViewControllers contain the logic for both the UITableViewDatasource and the UITableViewDelegate. This quickly leads to file bloat and becomes unmanageable. Not only will the file be huge it’s going to be pretty difficult to test as the Delegate and Datasource are very tightly coupled to what should essentially be the View.

A Solution

One solution to this problem is to move them into separate classes. The size of the UITableViewController will be reduced and testing can be performed on each isolated component.

This is not a great deal of work either:

  • Create two new classes, Datasource and Delegate.
  • Copy the code across to each file.
  • Create two properties inside the UIViewController.
@property (strong, nonatomic) id<UITableViewDataSource> dataSource;@property (strong, nonatomic) id<UITableViewDelegate> delegate;
  • Create the Datasource and Delegate instances.
  • Assign them to the UITableView.
self.tableView.dataSource = self.dataSource;self.tableView.delegate = self.delegate;

Congratulations, you now have decoupled the Datasource and Delegate.

This approach is enough to get you off the ground however it has a little flaw which I will discuss in part 2.

--

--

Nathan Hunston
Mobile Engineering

Mobile Software Engineer @CapitalOne working in their awesome Software Studio.