1

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

Is it possible to do something like NSVariableFromString?

casperOne
  • 73,706
  • 19
  • 184
  • 253
Popeye
  • 11,839
  • 9
  • 58
  • 91
  • I'm not actually trying to do anything I was just wondering. Could this really be done using the NSSelectorFromString? As when you are getting a variable you are actually calling the getter for it. – Popeye Aug 03 '12 at 10:50
  • Not all variables have selectors, only properties. – Stephen Darlington Aug 03 '12 at 11:01
  • 1
    It wasn't me who voted - but it's hard to think of any real world, useful reason to do what you asked and you haven't provided a use case either... – Paul.s Aug 03 '12 at 12:14
  • 1
    @Paul.s OK. I am grateful for the response. +1. The reason I was wondering was because I have just had to use NSSelectorFromString to dynamically change the method it needs to call based on some settings. I don't need it at the moment but I can see myself needing something like it in the near future and I thought I would get the question asked now. – Popeye Aug 03 '12 at 12:24
  • possible duplicate of [Syntax help - Variable as object name](http://stackoverflow.com/questions/7940809/syntax-help-variable-as-object-name) – jscs Aug 03 '12 at 17:11
  • 1
    @JoshCaswell I disagree these two questions are not the same. – Popeye Aug 05 '12 at 22:17

3 Answers3

4

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

JeremyP
  • 84,577
  • 15
  • 123
  • 161
3

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.

Jody Hagins
  • 27,943
  • 6
  • 58
  • 87
  • `object_getInstanceVariable` "is unavailable: not available in automatic reference counting mode" any alternatives? – Alex Gray Oct 28 '12 at 18:56
  • 1
    @alexgray That appears to be new with the latest update. I can't find any documentation on the change. However, you can still obtain the `IVar` reference with `class_getInstanceVariable`. – Jody Hagins Oct 28 '12 at 20:04
1

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.

Community
  • 1
  • 1
Stephen Darlington
  • 51,577
  • 12
  • 107
  • 152