Problem of a ViewController

A ViewController is usually a very large file. It does a lot of things to “manage the screen” and so can get bloated up. Many problems can happen:

1. A tableViewController can include many functions which make the file huge:

– tableViewDataSource (numberOfSections, numberOfRowsInSection, cellForRow, canEditRow, canMoveRow, titleForHeader …)

– tableViewDelegate (heightForFooter/Header/Row, estimatedHeightForFooter/Header/Row, viewForFooter/Header, and more functions should/will/did …)

2. Each of these functions can be huge if there are many TableViews

3. ViewController actually becomes a DataSource as it stores all the data itself.

There can be many other problems…

Separation as Solution

1. Separate all the Delegate and DataSource functions into another class, maybe called DataController / TableSource … defined as

typedef NSObject<UITableViewDataSource, UITableViewDelegate> UITableViewDataController;

The reason that we can’t split Delegate and DataSource into 2 separate classes is some Delegate functions need to access DataSource.

2. Usually the DataController will have a public property (weak) tableView that can be assigned by the ViewController. It also needs a Delegate which is the ViewController, serving as a callback, especially for operations working on other (not tableView) objects – like navigationController etc..





Similar to TableView, CollectionView has

UICollectionViewDelegate and UIViewControllerDataSource , however as the CollectionView you also need to implement a Layout protocol.

The Delegate and DataSource can be separated as they are not tightly coupled as in TableView.