views:

141

answers:

2

This is so simple it's driving me crazy that I can't find an answer.

How can a method refer to the instance that invoked it?

Example: in some method of class alpha, I have "[bravo charley]"

I want to have the charley method do "[alpha-instance delta];" with the particular instance of alpha that did the "[bravo charley]". But charley doesn't know anything about alpha or its instances.

In other words, how can I get a reference to alpha-instance from within the charley method that was invoked by a method in alpha-instance?

I could do something like

in bravo.h:
    -(id) charley:(id)invoker;
in alpha.m:
    [bravo charley:self];

and then "[invoker delta];" in the charley method, but that seems pretty ugly.

+9  A: 

The common idiom for acomplishing this is to pass a parameter called sender with the message, more or less like in your example. This is for example how methods bound as user interface actions are specified -- e.g.

-(IBAction)doTheThing:(id)sender

There is no built in way to get hold of the object that sent the message, and it's very rarely needed.

Theo
Thanks. No wonder I couldn't find a built-in way to do it!
Beginner Still
+1  A: 

Just to clarify, a method may not always be invoked by another object, so the runtime wouldn't be able to provide such information reliably anyway. For example,


int main (int argc, char *argv[])
{
    SEL releaserSel = @selector(release);

    NSObject *someObject = [[NSObject alloc] init];

    IMP releaserImp = [someObject methodForSelector:releaserSel];

    releaserImp (someObject, releaserSel);

    // someObject has been released!
    return 0;
}

It's probably not as rare as you'd think too. Invoking a method directly is much faster than sending a message (it helps in situations where the same message is being sent to the same object over and over).

dreamlax