Most of the time we see in tutorials, code examples and even apple starter project our view controller being the delegate and the datasource of some tableview. Although I’m not saying this approach is wrong, it is not the best for every situation, and even in the worst cases we most of the time use this approach. As an example, if our viewcontroller has two tableviews, generally we see a lot of if code to control the logic for each tableview. Even, when we got only one tableview, but this table can be ordered, sorted, searched, and displayed in different formats, our code gets full of if codes. This can lead to a huge amount of bugs, work-arounds and finally to an confused and impossible code to maintain.
In those cases we can always use our good OOP (object orientation programming) knowledge.
Objective-C has a very good design pattern called “Delegate”. In this pattern you delegate some functions to another class to execute. In IOS development we use delegates all the time. But the delegate of a tableview does not necessary need to be the viewcontroller container of the tableview. We can create other NSObject classes to be the delegate for a tableview.
“But what kind of benefits do i get doing that?” you must be thinking. Well, using this pattern you can create a different delegate for each state of your table.
In in the state1 your tableview does not have sections and your cells should only display text, you create a delegate for that.
And if in the state2 your tableview should have sections, and each row should display also a detail for each row, you don’t need to create a lot of ifs. Just create another delegate, assign it as the new delegate for you tableview, and call the reloadData message of your tableview. Ad you are done.
Here goes an example of two datasources delegators: