将调用函数的名称打印到调试日志
Objective-C 的运行时似乎相当健壮,所以我想知道是否有一种方法可以记录调用当前函数的函数的名称(用于调试目的)。
我的情况是,一堆东西分配给一个属性,而不是每次都设置断点并检查调用堆栈,我只想 NSLog
设置该属性的函数的名称属性以及新值。
那么是否可以在运行时访问调用堆栈呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
试试这个:
Try this:
好问题。结合上面 Jeremy 的答案和我们经常用于调试的内容,您将得到一个像这样的漂亮字符串:
Great Question. Combining Jeremy's Answer above and what we always use for our debugging, you'll get a nice string like this:
没有获取发件人的设施。或者,至少,没有什么以 Objective-C 为中心的。
不过,还有几种选择。
首先,您可以使用 GDB 命令。转到 GDB 控制台并执行以下操作:
或者,您可以使用 dtrace。这很难。或者您可以使用 Instruments,这使得 dtrace 更容易一些。
或者您可以使用 backtrace() 函数。请参阅 backtrace 手册页 (x-man-page://backtrace)。
There is no facility for getting the sender. Or, at least, nothing centric to Objective-C.
There are a couple of alternatives, though.
First, you could use GDB commands. Go to the GDB console and do something like:
Alternatively, you could use dtrace. This is hard. Or you could use Instruments which makes dtrace somewhat easier.
Or you could use the backtrace() function. See the backtrace man page (x-man-page://backtrace).
有一个名为
__PRETTY_FUNCTION__
的 C 宏,它将返回带有当前函数名称的 C 字符串。如果您想将其转换为 NSString 以便轻松打印到 NSLog,您可以创建一个宏,我在项目中一直使用它。
There is a C macro called
__PRETTY_FUNCTION__
that will return a C-String with the name of the current function. If you would like to convert that to an NSString for easily printing to NSLog, you can create a macro withI use it all the time in my projects.