Xcode / Objective-c – 如何以编程方式查找给定方法的调用者

前端之家收集整理的这篇文章主要介绍了Xcode / Objective-c – 如何以编程方式查找给定方法的调用者前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
xcode中,我能够使用图片中的按钮找到给定方法调用者.

是否可以在运行时进行?

就像是:

-(NSArray *)getCallersOfFoo {

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

}

-(void)foo {...}

解决方法

不完全是答案,但它可能有所帮助.此方法将为您提供打印输出堆栈或调用区域中的调用方.您可以修改它们当然可以随意使用这些值.

代码有点“被盗”,但我没有提到哪里.

#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> %@",NSStringFromSelector(_cmd)); \
} \
} while(0)

编辑:你可能想要这样的东西:

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

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

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

你可能会发现another Q&A here on SO非常有用.

猜你在找的Xcode相关文章