denniss
denniss

Reputation: 17589

How does UITableViewController knows its dataSource and delegate

I am following the BigNerdRanch iOS Programming book and I am on this one chapter that deals with UITableViewController. I have been wondering however where UITableViewController finds out about its delegate and dataSource. Currently I have it as

@interface ItemsViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>

But there is nothing that looks like:

[self.tableView setDelegate:self]

I am just wondering how the UITableViewController finds out about its delegate and dataSource

Upvotes: 1

Views: 4218

Answers (3)

benzado
benzado

Reputation: 84338

If you were setting up the UITableView yourself, you would have to point it to a delegate and data source.

UITableViewController sets up the UITableView and sets the delegate and dataSource properties to itself. When you subclass UITableViewController, you get this behavior for free.

Your question is flawed because UITableViewController doesn't have a dataSource and delegate, the UITableView it is controlling does. And the UITableViewController is the dataSource and delegate because it sets things up that way.

Upvotes: 5

Lefteris
Lefteris

Reputation: 14677

First of all the declaration:

@interface ItemsViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>

is only an indication that your View Controller is responsible for providing DataSource and Delegate methods. This is just an hint (you are just saying that your view is conforming to that protocols) to someone viewing your code and a hint to Xcode that you need to provided the required protocol implementations (else Xcode will give you a warning that you haven't implemented the datasource and delegate methods, and again only for the required and not optional methods).

You actually are setting the datasource and delegate of the TableView in the Interface Builder. Click on the TableView in IB, select from the right pane the Outlets option, then click on datasource and drag over to the "File's Owner" to set the datasource. Same for the delegate.

If you are creating the table in code, you need to declare the datasource and delegate yourself, this way:

tableview.datasource = self;
tableview.delegate = self;

Upvotes: 1

Michael Dautermann
Michael Dautermann

Reputation: 89509

You either set the delegate and dataSource on the table view object (in the xib or storyboard file) via Interface Builder (within Xcode) or programatically, via ".delegate =" ([self.tableView setDelegate: _____) and ".datasource=".

Note, you're setting these things on the table view managed by the table view controller (i.e. two distinct objects).

Upvotes: 1

Related Questions