Dynamically accessing local variables in Objective

2020-04-12 12:19发布

问题:

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