开发者

Why some method declarations in the UITableViewDataSource protocol are preceded by "tableView:(UITableView *)tableview?

开发者 https://www.devze.com 2022-12-18 21:53 出处:网络
The formulation of the question may be confusing. I do understand why it is useful for a method like cellForRowAtIndexPath to receive a pointer the relevant UITableView.

The formulation of the question may be confusing. I do understand why it is useful for a method like cellForRowAtIndexPath to receive a pointer the relevant UITableView.

What I don't understand is more Objective-C wise: I would like to put a name on is this special way of declaring methods?

Like if an object (e.g. UITableView) that have some internal protocol (e.g. UITableViewDataSource) would send messages to the implementers using a special way of referencing itself.

I.E. I开发者_开发百科nstead of passing a reference to itself as a regular Objective-C message argument, the UITableView is using that special syntax?


Edit

There's quite a long discussion in the comments to this answer, which refined the original question. I'll post the salient points here to help others who may have similar questions.

It boiled down to a confusion between two methods,

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

The first method is an instance method of UITableView which returns a UITableViewCell for a given index path. This method is called on a table view object.

The second method is a datasource method declared in the UITableViewDataSource protocol that asks for a UITableViewCell for a given index path.

The important difference is that the first is called on a table view instance by any class that may want a reference to a table cell, and the second is called by a table view instance on a data source class to ask for a cell to display at the given index path.

I hope this helps.


Most delegate/datasource protocols in Cocoa/Cocoa Touch follow this pattern. It's a way of saying something like "this table view wants this data".

Consider something like a text field object. You may have an interface with many text field objects that all report to the same delegate to define their behaviour for certain actions. By passing itself as an argument in a method to the delegate, the delegate knows which text field is calling the method.

I'm not sure I fully understand what you're asking, but this is the way objects inform their delegates/datasources which exact object is sending the method. In the case of UITableView it is less obvious because often there is only one table view per table view controller, but the text field example I gave should outline this fact.

0

精彩评论

暂无评论...
验证码 换一张
取 消