views:

137

answers:

2

i read a lot about objective c delegate but didn't get clear idea.Can anyone explain it with a good and precise example so that i can understand it. Advanced thanks for your reply.

+1  A: 

A delegate in Objective-C is essentially a pointer to an object that another class uses to notify it of events.

For example, class A asks you for a delegate. You tell it [this] instance of class B will do.

[a setDelegate:b];

Then in class A's methods and actions, it will invoke pre-defined methods on your delegate object like so:

-(void)actionFinished:(id)sender
{
    [delegate a:self finishedWithResult:RESULT_OK];
}

So your delegate object should be implemented to respond to that message:

-(void)a:(A *)a finishedWithResult:(int)result { /* respond */ }
Nick Bedford
+1  A: 

Here's an answer I gave about delegates and how they work: http://stackoverflow.com/questions/1089737/parsing-xml-in-cocoa/1090170#1090170

It's most commonly known as the "Strategy Pattern", and you can read all about it on Wikipedia: http://en.wikipedia.org/wiki/Strategy_pattern

It is also a slight variation on object composition: http://en.wikipedia.org/wiki/Object_composition

Dave DeLong