Avba
Avba

Reputation: 15266

Xcode / Objective-c - How to find the callers of a given method programmatically

In xcode I am able to find the callers of a given method using the button in the picture.

Is it possible to do at runtime?

Something like:

-(NSArray *)getCallersOfFoo {

  // is it possible to find the callers of the method foo?

}

-(void)foo {...}

enter image description here

Upvotes: 4

Views: 532

Answers (2)

Rok Jarc
Rok Jarc

Reputation: 18865

Not exactly an answer, but it might help. This methods will give you a printout of stack or of caller in debug area. You can modify them of course to use the values as you please.

Code is kind of 'stolen' but i have no reference to where from.

#define SHOW_STACK NSLog(@"%@",[NSThread callStackSymbols])

#define SHOW_CALLER \
do {                \
NSArray *syms = [NSThread  callStackSymbols]; \
if ([syms count] > 1) { \
    NSLog(@"<%@ %p> %@ - caller: %@ ", [self class], self, NSStringFromSelector(_cmd),[syms objectAtIndex:1]); \
} else { \
    NSLog(@"<%@ %p> %@", [self class], self, NSStringFromSelector(_cmd)); \
} \
} while(0)

EDIT: you would probably want something like this:

NSString *caller = nil;
NSArray *syms = [NSThread  callStackSymbols];

if (syms.count > 1)
{
    caller = syms[1];
}

if (caller.length)
{
    NSLog(@"%s called by %@",
          __PRETTY_FUNCTION__,
          caller);
}

There is another Q&A here on SO you might find very useful.

Upvotes: 1

Eiko
Eiko

Reputation: 25632

The short answer: no.

The long answer: well, you can mess around with the call stack, and then put in some more effort to make use of what you get. But it's most probably not what you're looking for.

Generally, the method should not care at all how it's called.

Upvotes: 0

Related Questions