Take the 2-minute tour ×

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);

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

    return objectThatCalledThisMethod;

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

share|improve this question

4 Answers 4

up vote 11 down vote accepted

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.

share|improve this answer

No, you cannot determine what object called you. Well, technically, it might be possible to poke around the stack back trace, but certainly its not practical for real code.

If you look at most of the delegate methods, you can see that the standard delegate call formats look like this:

- (BOOL) windowShouldClose:(id)window;
- (void) windowWillMove:(NSNotification *)notification;

Note how the window (caller) is passed as the first argument, and how "window" is the first part of the method name. In the last case, the window caller is implicit in the NSNotification (notification.object is the window).

share|improve this answer

You could try and derive your own class from NSInvocation that carries the caller information. Or wrap a class around NSInvocation reimplementing some of the calls in there.

share|improve this answer
NSInvocation also doesn't have anything about the caller — just target, selector, and arguments. –  Quinn Taylor Jul 12 '09 at 14:52
That is why i suggested deriving a new class or wrapping it around, this might at least give you a consistent way to pass the sender into the calling function or possibly construct a data structure where the information can be pulled from at the receivers end. It does depend on what he is trying to accomplish –  Harald Scheirich Jul 12 '09 at 15:40

I hope that this helps:

    NSMutableArray *array = [NSMutableArray arrayWithArray:[origen  componentsSeparatedByCharactersInSet:separatorSet]];
    [array removeObject:@""];

    NSLog(@"Pila = %@", [array objectAtIndex:0]);
    NSLog(@"Line caller = %@", [array objectAtIndex:5]);
share|improve this answer

Your Answer


