tags:

views:

232

answers:

3

From reference: http://stackoverflow.com/questions/1408774/objective-c-delegate-explanation-with-example

NICK wrote:

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

[a setDelegate:b];

What is a? Is it a instance of Class of A?

+1  A: 

Sending messages to objects using Objective-C is done using the square brackets.

You have instance methods, they are denoted with a - (minus) sign ahead of the return type of the method, like so:

- (void)setDelegate:(id <SomeDelegateProtocol>)delegate;

Alternatively you have the class methods denoted with a + (plus) sign:

+ (NSArray *)arrayWithObject:(id)object;

The first text within the brackets stands for the receiver of that message, in case of an instance message this will be an object pointer. Otherwise, when you deal with a class message, you use the class it's name.

So a is indeed a pointer for an instance, probably of class A (well, it actually is just the name of the variable the object is assigned to. It can be of any class).

JoostK
A: 

This example is presuming that we have two classes, class A and class B, and that we have one instance of each of them; a is an instance of A, and b is an instance of B:

ClassA *a = [[[ClassA alloc] init] autorelease];
ClassB *b = [[[ClassB alloc] init] autorelease];

We're also presuming that class A has some kind of delegate variable, and a method setDelegate: that changes the value of that variable. In general, a delegate is an instance of an object that receives messages about another object's activities or defines its behavior in some way. So, for example, if class A has some method doFoo, class B might have a delegate method a:didFoo: that gets called from class A whenever it does Foo.

But before the delegate can fulfill its purpose, the object it's to receive messages about has to know that it has a delegate. So we have to set our instance of class B as class A's delegate by using class A's setDelegate: method:

[a setDelegate:b];
Tim
A: 

The short answer is:

Yes.

Hope that clears things up. For longer answers see Tim & JoostK.

If you're not familiar with Obj-C's message passing syntax you should probably get more practice with that before worrying about delegates. Once you understand message passing, delegates are straightforward.

Phil Nash