Why is it necessary to declare datasource/delegate twice

59 Views Asked by At

After I add a Table View to a View Controller, I control-drag twice from the TV to the VC in Interface Builder to specify that the VC is the datasource and delegate of the Table View.

In the View Controller I then have to specify the same in the class definition or View Controller extension.

Why is this? Isn't this redundant?

Thanks.

2

There are 2 best solutions below

0
On BEST ANSWER

Not at all. What you are doing is two different things.

In the extension you are telling the compiler "this class conforms to the UITableViewDatasource and UITableViewDelegate protocols and so can be used as such for a UITableView".

In Interface Builder you are telling the UITableView "this class here is what I want you to use as your datasource and delegate".

0
On

This is of course not redundant.

As you can tell from the difference in the names, "delegate" and "data source" are different things.

A data source answers questions about the data that the table view displays. For instance, how many rows are there in each section? How many sections are there? How long are the table view cells? What is the header view and footer view for each section?

On the other hand, a delegate answers questions about the behaviour of the table view. For instance, what should be done when the user selects a cell? What should be done when the user deselects a cell? What should be done when the user ends editing?

Because of the very different functionalities of data sources and delegates, a class might only be a data source but not a delegate, or vice versa. That's why you drag twice, once to say that the VC is the data source and once to say that the VC is the delegate.

However, not just any VCs can be data sources and delegates. You must tell the compiler that your VC has the ability to be a data source and a delegate. That's why you write:

class MyVC: UITableViewDelegate, UITableViewDataSource {}

If you think this is two troublesome, use a UITableViewController if you can.