Dynamically accessing local variables in Objective-C runtime

可紊 提交于 2019-12-20 03:14:13

问题


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

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).

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.


回答1:


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.

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...



来源:https://stackoverflow.com/questions/23748395/dynamically-accessing-local-variables-in-objective-c-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!