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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With