ObjectiveC中打印Call Stack的若干方法

来源:互联网 发布:eclipse maven mac 编辑:程序博客网 时间:2024/05/16 00:53

动因

虽然lldb已经内置命令可以打印当前Call stack,但还是会遇到需要通过代码获取调用栈信息的时候。

使用NSThread

NSLog(@"%@", [NSThread callStackSymbols]);

通过backtrace_symbols_fd

#import <execinfo.h>#import <unistd.h>void PrintCallStack() {  void *stackAdresses[32];  int stackSize = backtrace(stackAdresses, 32);  backtrace_symbols_fd(stackAdresses, stackSize, STDOUT_FILENO);}

通过NSException

@catch (NSException *exception){    NSLog(@"%@", [exception callStackSymbols]);}当然也可以在UncaughtExceptionHandler中拿到NSExceptionNSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);void uncaughtExceptionHandler(NSException *exception){    NSLog(@"reason:%@ exception nanme:%@",[exception reason], [exception name]);    NSLog(@"call stack:%@",[exception callStackSymbols]);}

要注意的是,如果IDE中已经添加过All exceptions Breakpoint, 那么 UncaughtExceptionHandler不再生效

通过ExceptionHandling

由于不支持iOS 不细说了
具体参考Apple developer 文档

0 0
原创粉丝点击