-->

Can I do NSVariableFromString like NSClassFromStri

2020-03-30 08:24发布

问题:

Right so I have noticed that you can do NSClassFromString and NSSelectorFromString.

Is it possible to do something like NSVariableFromString?

回答1:

The objective C runtime has lots of goodies for your consumption.

If you want an iVar, you can call object_getInstanceVariable with a string name.

If you want variables, it's a bit more work, and they have to be globally visible to the linker. You can use CFBundleGetDataPointerForName for that purpose.

Be sure to read the documentation for restrictions and specific information about runtime information, and the availability of stuff on different platforms.



回答2:

No. Compiled applications don't contain variable names except when debug info is included and it usually isn't for release applications.



回答3:

You can get values from strings using NSScanner but, as JemeryP notes, at runtime variable names have generally been converted to pointers and memory addresses.