Separate Delegate and DataSource of UITableView from your ViewController

Step 1 demo – simple table
step 2 demo – pull out the data source
step 3 demo – pull out table view delegates

Step 1

Step 2 – pulling out the Data Source

In order to declare a data source, we first create an object that houses the data to represent the rows of data in your table view. Declare the protocol of UITableViewDataSource. This is so that your class conforms to it. And other delegates can then safely point to your object.

In the implementation, declare your data container, such as an array of strings.
Initialize your array in the initializer.

Then, in order satisfy the protocol that we conformed to (UITableViewDataSource), make sure you implement its needed methods.
Specifically, we implement

Declare your Data class in ViewController, point dataSource to it

ViewController.m

We now declare our data class (which safely conforms to UITableViewDataSource )as a property.

Initialize the data object. Then we point the table view’s data source to it.

Now if you run it, all UITableViewDelegate delegate messages are sent to your MyData object.

Step 3 – Pulling out the UITableViewDelegate

Now we’re going to create a View object that takes care of all the UITableViewDelegate delegates.

We implement delegate methods:

We log which row is selected.

We also check what kind of cell it is. Then we do something unique according to the cell type.

Declare your MyView property. It should conform to protocol UITableViewDelegate.

ViewController.m

Then we instantiate it. Make sure your table view’s delegate points to the MyView object. Now all delegates sent from table view for its delegate functionality will be sent to your MyView object to be processed.

Notice that your ViewController is now nice and clean, with a clear separation of concern between data source delegates and tableview delegates.