I think I fully understand the concept of delegation, my question is that when we do:
class someViewController : UIViewController, UITableViewDelegate{
}
would it ever be possible that we wouldn't want to set tableView.delegate
to self
?
If there isn't any chance then why is Xcode forcing us to do some extra work here?
If there is a chance that tableView.delegate
is set to something other than self
...well what is that? Can you please provide some examples?
Yes, if you would implement datasource and delegate in it's own class.
to allow as much freedom in our architectures as possible.
An example with separate classes for datasource and delegate.
This allows higher reusability and favours composition over inheritance, if you'd allow view controllers to hold different implementations of delegate and datasource.
You deal with smaller classes and those are easier to test and maintain.
It is even possible to design complete apps, that don't need any view controller subclasses.
datasource/delegate design can be as sophisticated as you like.
As an example I want to show you a new project of mine: TaCoPopulator. It is a framework to populate table view and collection views transparently by splitting it up in distinct task to follow the SOLID Principles:
When mentioning that
tableView.delegate = self
ortableView.dataSource = self
in the desired ViewController, that's means the ViewController is saying "I am responsible for implementing those delegation/dataSource methods", means that this ViewController (self
) is taking care of providing the needed method to let tableView knows how it should looks/behaves.Referring to your questions:
Actually it's possible, but this causes to let the tableView appears as an empty tableView (no rows in it), because no one is telling it about how it should looks/behave.
Yes you can, tableView.dataSource/delegate not necessary to be assigned to the same Viewcontroller that contains this tableView (but I find it more readable and understandable).
For example:
In the following code snippets, I assigning the dataSource of the tableView to another separated class (which is not even a UIViewController) on a different .swift file and it completely works fine:
Handler Class:
The output works fine as it should.
What's
tableView.delegate
? Your classsomeViewController
is not a subclass ofUITableViewController
(and does not have atableView
property). It does not even know that you handle a table view.The fact that your type declaration conforms to
UITableViewDelegate
does not make it obvious on which actual table view instance it should be set.Often times it's wise to split up functionality into multiple types to reduce the complexity of the view controller. Your
someViewController
might have aviewModel
property that handles all thing regarding the table view.