Some methods of printing call stack in objectivec

Time:2022-6-10

agent

Although lldb has built-in commands to print the current call stack, it still needs to obtain the call stack information through code.

Use nsthread

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

be careful

This method is invisible to the system call stack on the device.

Via 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);
}

Via nsexception

@catch (NSException *exception)
{
    NSLog(@"%@", [exception callStackSymbols]);
}
Of course, you can also get the nsexception in uncaughtexceptionhandler

NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
void uncaughtExceptionHandler(NSException *exception)
{
    NSLog(@"reason:%@ exception nanme:%@",[exception reason], [exception name]);
    NSLog(@"call stack:%@",[exception callStackSymbols]);
}

Note that if all exceptions breakpoint has been added to the IDE, uncaughtexceptionhandler will no longer be effective

Through exceptionhandling

I won’t go into details because I don’t support IOS
Refer to Apple Developer for detailsfile

Originally written in segmentfaultlink