Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the name of the calling function to the debug log

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?

like image 777
Brian Avatar asked Oct 28 '10 20:10

Brian


People also ask

What is the caller of a function?

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.

Which of the following methods can be used to get the caller of a function a funk?

You can use Function. Caller to get the calling function.

What is function caller in JavaScript?

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.


2 Answers

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__); } 
like image 168
Jeremy W. Sherman Avatar answered Sep 21 '22 13:09

Jeremy W. Sherman


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));  } 
like image 28
Blitz Avatar answered Sep 20 '22 13:09

Blitz