4

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

Popeye
  • 11,839
  • 9
  • 58
  • 91
Avba
  • 14,822
  • 20
  • 92
  • 192
  • maybe this can help http://stackoverflow.com/questions/11916016/how-does-the-objective-c-runtime-retrieve-the-list-of-classes-and-methods – iamIcarus Jul 21 '15 at 10:53
  • This is something that Xcode is doing from an "outside" view of the code. It's analyzing the source via partial compilation. A program can't generally do that to itself at runtime, largely because the source code is not available. You need to explain the high-level purpose for what you're trying to do in order to get meaningful answers. – Ken Thomases Jul 21 '15 at 11:12
  • I want to swizzle a method and execute some code for a particular caller – Avba Jul 21 '15 at 11:27

2 Answers2

1

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.

Community
  • 1
  • 1
Rok Jarc
  • 18,765
  • 9
  • 69
  • 124
0

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.

Eiko
  • 25,601
  • 15
  • 56
  • 71