4

I was asked this question in an interview. For eg: UITableviewDelegate protocol has CellForRowAtIndexpath. Why make it a delegate method in a protocol not a method in the UITableView class and call it directly?

3 Answers 3

5

Protocols are used to define a set of methods to interact with regardless of the type of the object implementing them. It allows you to easily interchange external resources that the view interacts with and reduces the overall coupling of your code. This is in contrast to directly calling the resource with knowledge of its type.

1

By not putting the -[tableView:cellForRowAtIndexPath:] in the UITableViewController class, one can write another class to use as datasource (cellForRow is in the datasource). This can be useful for code organization or code-reuse.

By putting it in a protocol, the class can have any superclass: useful when subclassing your own datasources or delegates. It also gives to ability to add in the datasource anywhere you want, even in the app delegate or a view subclass (don't do this).

0

Here's what Apple have to say about it:

Delegation

Delegation is a mechanism by which a host object embeds a weak reference (weak in the sense that it’s a simple pointer reference, unretained) to another object—its delegate—and periodically sends messages to the delegate when it requires its input for a task. The host object is generally an “off-the-shelf” framework object (such as an NSWindow or NSXMLParser object) that is seeking to accomplish something, but can only do so in a generic fashion. The delegate, which is almost always an instance of a custom class, acts in coordination with the host object, supplying program-specific behavior at certain points in the task. Thus delegation makes it possible to modify or extend the behavior of another object without the need for subclassing.

So, in this case, you want to supply a custom-built cell, but you don't want to subclass the UITableView to do so. Any class that conforms to the protocol can supply the custom cell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.