Oscar Gomez
Oscar Gomez

Reputation: 18488

UIViewController as datasource and delegate of UITableView without conforming to protocols?

I was reviewing some of my code, and suddenly I realized that a UIViewController which has UITableView and is the datasource and delegate of this UITableView does not declare the protocols <UITableViewDataSource, UITableViewDelegate>, but instead simply has the methods but never declares the protocols.

How is this even working?, per the documentation:

dataSource
The object that acts as the data source of the receiving table view.
@property(nonatomic, assign) id<UITableViewDataSource> dataSource
Discussion
The data source must adopt the UITableViewDataSource protocol. The data source is not retained.
delegate
The object that acts as the delegate of the receiving table view.
@property(nonatomic, assign) id<UITableViewDelegate> delegate
Discussion
The delegate must adopt the UITableViewDelegate protocol. The delegate is not retained.

There are NO warnings of any type, I do have the necessary methods of course to make this work and everything works perfectly, why is this working?. I am not inheriting from UITableViewController which I know declares this protocols, this is just a UIViewController subclass.

EDIT: Apparently IB will not give you any warnings if it is set up there, it does as expected on code though. I believe IB should also give you the warning, but I guess not.

Upvotes: 2

Views: 1889

Answers (2)

jbat100
jbat100

Reputation: 16827

As long as you implement the methods that are marked as required by the UITableViewDelegate and UITableViewDataSource (as in none for UITableViewDelegate and two for UITableViewDataSource) then you are fine. The tableView will check with respondsToSelector for optional methods. Are you doing your connections in interface builder? If you do it in code there should be a little warning saying your class does not conform to UITableViewDataSource and UITableViewDelegate, but at the end of the day if your object responds to the required messages at run-time, it will work.

Upvotes: 2

Michael Dautermann
Michael Dautermann

Reputation: 89519

What's happening is that the table view is sending data source and delegate messages to the designated objects, in the hopes that the designated objects conform to the (non-declared) protocols.

Adding UITableViewDataSource & UITableViewDelegate to your interface .h files gives you type checking and conformance (i.e. warnings if you don't implement "required" methods, etc).

There are probably more official descriptions for what I just summarized above.

b.t.w., your question is a dupe of this one

UITableView without <UITableViewDelegate, UITableViewDataSource> still works!

Upvotes: 1

Related Questions