问题描述
我想编写一个调试函数或方法来帮助打印有用的信息。当它被调用时,我需要:
I want to write a debug function or method that will help print useful information. When it is called, I need:
- 调用对象的内存地址(如果对象调用)
- 调用者的方法签名(或方法的名称)或函数的名称
- 拥有该方法或函数的类名称
是否可以获取此信息而不传递整个参数?
Is it possible to get this information without passing a whole bunch of parameters?
想要做的事情:
debug();
然后进入每个方法和函数,帮助打印出有用的信息。 / p>
which then goes into every method and function, and helps printing out useful informations about what's going on.
推荐答案
我的第一本能是建议使用 gdb
大多数信息在堆栈跟踪中可用。
My first instinct would be to suggest using gdb
and breakpoints, since most of that information is available in a stack trace. However, if you really want to see it printed, there are ways to approximate what you're talking about
预处理器识别 __PRETTY_FUNCTION __
宏,用于打印函数/方法名称,它适用于Objective-C方法。如果在每个感兴趣的方法上打印方法名和 self
的值,你几乎生成了一个穷人的堆栈跟踪。
The preprocessor recognizes the __PRETTY_FUNCTION__
macro for printing the function/method name, and it works well for Objective-C methods. If you print the method name and the value of self
at each method of interest, you've pretty much generated a poor man's stack trace.
尝试在标题中包含 #define
,每个文件都包含:
Try including a #define
like this in a header that every file that wants it includes:
#define METHOD() printf("%s\t0x%x\n", __PRETTY_FUNCTION__, (unsigned int)self)
然后只要在打印该信息时包括此行即可:
Then just include this line whenever you want to print that information:
METHOD();
输出将如下所示:
-[MyClass initWithFoo:bar:] 0x12345678
我提到,这种类型的方法可能会产生大量的输出,而gdb可能是一个更务实的选择。
As I mentioned, this type of approach is likely to produce huge amounts of output, and gdb is probably a more pragmatic option.
这篇关于如何找出谁是方法或函数的调用者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!