Print the name of the calling function to the debug log

Brian picture Brian · Oct 28, 2010 · Viewed 10.4k times · Source

Objective-C's runtime seems to be rather robust, so I was wondering if there's a way to log the name of the function that called the current function (for debugging purposes).

My situation is that a bunch of things assign to a property, and rather than set a breakpoint and examine the call stack each time, I'd like to just NSLog the name of the function that is setting the property, along with the new value.

So is it possible to get access to the call stack at runtime?

Answer

Jeremy W. Sherman picture Jeremy W. Sherman · Oct 28, 2010

Try this:

#include <execinfo.h>

void *addr[2];
int nframes = backtrace(addr, sizeof(addr)/sizeof(*addr));
if (nframes > 1) {
    char **syms = backtrace_symbols(addr, nframes);
    NSLog(@"%s: caller: %s", __func__, syms[1]);
    free(syms);
} else {
    NSLog(@"%s: *** Failed to generate backtrace.", __func__);
}