在Objective-C运行时中动态访问局部变量 [英] Dynamically accessing local variables in Objective-C runtime

查看:76
本文介绍了在Objective-C运行时中动态访问局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过Xcode连接到调试器时,LLDB提供了一个有用的局部变量视图(屏幕截图的左下方):

When attached to the debugger via Xcode, LLDB provides a useful view of local variables (the bottom left of the screenshot):

我发现了一个LLDB命令frame variable(和gdb的info locals),该命令提供了局部变量列表(如上图右侧所示).

I found an LLDB command frame variable (and gdb's info locals) that provides a list of the local variables (as seen in the right side of the screenshot above).

我希望此功能可以在运行时在设备上执行.例如,我可以使用backtrace_symbols()访问堆栈跟踪,通过_cmd访问当前选择器,以及其他一些访问.

My hope is that this functionality is possible to perform on the device at runtime. For example, I can access the stack trace using backtrace_symbols(), the current selector via _cmd, and a few others.

有人在这方面有经验吗?预先感谢.

Has anyone had experience in this area? Thanks in advance.

推荐答案

Xcode/LLDB可以向您显示此信息,因为它们可以访问二进制文件(称为符号表)中的调试信息,这有助于了解二进制文件对应的内存位置您的源代码中的哪个名称.这些都在Objective-C运行时之外,并且在运行时中没有接口可以实现.

Xcode/LLDB can show you this information because they have access to debug information in the binary, called a symbol table, which help it understand what memory locations correspond to which names in your source code. This is all outside the Objective-C runtime, and there's no interface in the runtime to get at it.

尽管如此,这还有另一个原因无法解决.当您构建要在调试器中运行的代码时,编译器优化功能将关闭,因此您在代码中引用的所有变量都已存在.

There's another reason why this won't work, though. When you're building code to run in the debugger, compiler optimizations are turned off, so all the variables you reference in your code are there.

但是,当您为发行而构建时,通常,编译器优化会进入其中,并重新排列所有精心命名的局部变量,以使运行速度更快.它们甚至可能永远都不会存储在内存中,而只会存储在CPU寄存器中.如果优化程序可以证明自己不需要它们,那么它们可能根本就不存在.

When you build for release, though, generally the compiler optimizations get in there and re-arrange all your carefully named local variables to make things run faster. They might not even ever get stored in memory, just in CPU registers. Or they might not exist at all, if the optimizer can prove to itself that it doesn't need them.

我的建议是重新考虑您要解决的更大问题...

My advice is to think again about the larger problem you're trying to solve...

这篇关于在Objective-C运行时中动态访问局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆