views:

238

answers:

5

Example: When my method -fooBar gets called, I want it to log in the console which other method of which other class called it.

Right now, I only know how to log the method name of fooBar itself and it's class, with this:

_cmd

[self class]

Is this possible to figure out?

+1  A: 

It's not possible in the general case without actually walking the stack. There's not even a guarantee that another object send the message that called the method. For example, it could be called from a block in a signal handler.

Chuck
+1  A: 

This information can be obtained using DTrace.

arul
A: 

Make a macro that adds the __FUNCTION__ to the function name to the function call. This macro will then call your function with an extra parameter of a char* to the target function.

Robert
That assumes that you have control over the caller and can change the ABI between caller and callee by changing the argumentation, which is rarely the case.
bbum
+6  A: 

In fully optimized code, there is no 100% surefire way to determine the caller to a certain method. The compiler may employ a tail call optimization whereas the compiler effectively re-uses the caller's stack frame for the callee.

To see an example of this, set a breakpoint on any given method using gdb and look at the backtrace. Note that you don't see objc_msgSend() before every method call. That is because objc_msgSend() does a tail call to each method's implementation.

While you could compile your application non-optimized, you would need non-optimized versions of all of the system libraries to avoid just this one problem.

And this is just but one problem; in effect, you are asking "how do I re-invent CrashTracer or gdb?". A very hard problem upon which careers are made. Unless you want "debugging tools" to be your career, I would recommend against going down this road.

What question are you really trying to answer?

bbum
+2  A: 

See backtrace(3).

Peter Hosey