tags:

views:

113

answers:

3

I am new to objective C. I want to ask why "delegate" is needed in objective C. Could you provide me specific reasons, situations and code examples for this. I appreciate if anyone could help.

+4  A: 

"Delegate" is not a feature of Objective-C. Rather, it is a common pattern used by the Cocoa frameworks.

The basic idea is that when events happen, the object that detects that event doesn't have to handle it. Instead, it notifies a delegate.

To learn more, see the Cocoa Fundamentals Guide

Also see the Wikipedia "Delegation pattern" article, which includes an Objective-C example.

Kristopher Johnson
A: 

The TableView UI component, for instance, deals with displaying data like a table. What it displays however is not part of his responsibility, this behaviour can be added though by using delegates. The tableView has a delegate member which you can set, if that object implements methods which map to delegate methods of the tableView they will be called, otherwise they won't. This means that you don't need to implement everything, just what you need.

BennyM
+4  A: 

This idiom is how what we might call "callbacks" in other languages are typically done in ObjC. A class needs to react to a given situation (let's say a mouse click). The class is rather generic, and not coded with any domain-specific knowledge, so the policy for that action isn't written by that class. Hence it needs to "delegate" that action to your code. So it calls a method on an object you specify. Since your code presumably knows what it wants to do when you click the mouse.

Apparently there's even a Wikipedia article on this pattern, written by the kind of people who like to give special names to patterns. See: Delegation pattern.

asveikau