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?
A Function object's caller property returns the function that invoked the specified function. For strict, async function, and generator function callers, accessing the caller property throws an exception.
You can use Function. Caller to get the calling function.
The function. caller property of the JavaScript function object returns the function that invoked the specified function. It returns null if the function “f” was invoked by the top-level code in JavaScript. For functions like strict functions, async functions and generator function this method returns null.
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__); }
Great Question. Combining Jeremy's Answer above and what we always use for our debugging, you'll get a nice string like this:
NSArray *syms = [NSThread callStackSymbols]; if ([syms count] > 1) { NSLog(@"<%@ %p> %@ - caller: %@ ", [self class], self, NSStringFromSelector(_cmd),[syms objectAtIndex:1]); } else { NSLog(@"<%@ %p> %@", [self class], self, NSStringFromSelector(_cmd)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With