我可以收到发送 nil 对象消息的警告吗?
我知道在 Objective-C 中向 nil 对象发送消息是完全可以的。但是,我很好奇是否有任何运行时支持来标记此类情况。我可以看到这在测试/调试情况下很有用。
I'm aware that it's perfectly fine to send messages to nil objects in Objective-C. However, I am curious if there is any runtime support for flagging such situations. I can see this being useful in testing/debugging situations.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过一番摆弄调试器后,我发现了这一点。
您可以在 objc_msgSend 中设置断点,断点条件为第一个参数为零(接收者):
objc_msgSend
*(int*)($esp+4) == 0
运行时你的可执行文件会经常中断,因为向 nil 发送消息是很常见的。要了解正在发生的情况,您可以进一步配置断点:
p (char*)*(int*)($esp+8)
当您现在继续执行时,您将在调试器控制台中看到所有消息名称(被发送到 nil)。
以上所有内容仅适用于 Intel Mac(模拟器中的 32 位 Cocoa 或 Cocoa Touch)。 PPC 或 ARM 架构使用其他寄存器名称和调用约定。我将其作为练习留给您,以了解如何在这些平台上实现此功能;)
After a little fiddling with the debugger this is what I found out.
You can set a breakpoint in
objc_msgSend
with a breakpoint condition on the first argument to be zero (the receiver):objc_msgSend
*(int*)($esp+4) == 0
When you run your executable it will break very often since it's very common to send messages to nil. To get an overview of what's happening you can further configure your breakpoint:
p (char*)*(int*)($esp+8)
in the command fieldWhen you now continue execution, you will see all the message names (being sent to nil) in the debugger console.
All the above is working on Intel Macs only (32 bit Cocoa or Cocoa Touch in the simulator). PPC or ARM architectures use other register names and calling conventions. I leave it as an exercise to you to find out how to get this working on these platforms ;)
或者,您可以使用 dtrace:
使用 dtrace 记录消息到 nil 的日志
这可以是 也在 Instruments 中完成。
Alternatively, you can use dtrace:
Using dtrace to log traces messages-to-nil
And this can be done in Instruments, too.