本文翻译自:How do you print out a stack trace to the console/log in Cocoa?
我想在某些点记录调用跟踪,例如失败的断言或未捕获的异常。
参考:https://stackoom.com/question/VgX/如何将堆栈跟踪打印到Cocoa中的控制台-日志
n13's answer didn't quite work - I modified it slightly to come up with this n13的答案并不是很有效 - 我稍微修改了它以得出这个
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char *argv[])
{
@autoreleasepool {
int retval;
@try{
retval = UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
@catch (NSException *exception)
{
NSLog(@"Gosh!!! %@", [exception callStackSymbols]);
@throw;
}
return retval;
}
}
This pretty much tells you what to do. 这几乎告诉你该怎么做。
Essentially you need to set up the applications exception handling to log, something like: 基本上,您需要设置应用程序异常处理以进行记录,例如:
#import <ExceptionHandling/NSExceptionHandler.h>
[[NSExceptionHandler defaultExceptionHandler]
setExceptionHandlingMask: NSLogUncaughtExceptionMask |
NSLogUncaughtSystemExceptionMask |
NSLogUncaughtRuntimeErrorMask]
For exceptions, you can use the NSStackTraceKey member of the exception's userInfo dictionary to do this. 对于异常,您可以使用异常的userInfo字典的NSStackTraceKey成员来执行此操作。 See Controlling a Program's Response to Exceptions on Apple's website. 请参阅Apple网站上的控制程序对例外的响应 。
Cocoa already logs the stack trace on uncaught exceptions to the console although they're just raw memory addresses. Cocoa已经将未捕获的异常的堆栈跟踪记录到控制台,尽管它们只是原始内存地址。 If you want symbolic information in the console there's some sample code from Apple. 如果您想在控制台中获得符号信息,那么Apple会提供一些示例代码 。
If you want to generate a stack trace at an arbitrary point in your code (and you're on Leopard), see the backtrace man page. 如果要在代码中的任意点生成堆栈跟踪(并且您在Leopard上),请参阅backtrace手册页。 Before Leopard, you actually had to dig through the call stack itself. 在Leopard之前,你实际上不得不深入挖掘调用堆栈本身。
NSLog(@"%@",[NSThread callStackSymbols]);
此代码适用于任何线程。