Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Objective-C runtime features to determine where a method was called from?

Objective-C uses a sophisticated message-passing system when one object calls a method on another object. I want to know if it is possible, within the called method, to determine what the calling object was?

For example:

@implementation callingClass
- (void)performTest
{
    calledObject = [[[calledClass alloc] init] autorelease];
    id result = [calledObject calledMethod];

    assert(result == this);
}
@end

@implementation calledClass
- (id)calledMethod
{
    id objectThatCalledThisMethod = ... // <-- what goes here?

    return objectThatCalledThisMethod;
}
@end

What could I write in the commented line in order to make the assertion pass when I execute performTest?

like image 219
e.James Avatar asked Jul 12 '09 02:07

e.James


1 Answers

Not with the runtime. All message sends ultimately work out to a function call along the lines of objc_msgSend(id receiver, SEL selector, /*method arguments*/...). As you can see, no information is passed about the object sending the message. It's probably possible to determine the calling object by walking the stack, but that way lies madness. The only practical way to tell who called the method is to give it a sender argument like all IBAction methods have.

like image 110
Chuck Avatar answered Nov 15 '22 13:11

Chuck