1

Possible Duplicates:
Get an ivar or property from a NSString
Remove @“” from NSString or typecast NSString into variable name

Let's say I have:

MyClass *myVar = [[MyClass alloc] init];

and I have an NSString *myString = @"myVar";

Is there any way to retrieve the instance of the var based on the string I have?

Community
  • 1
  • 1
Tudor
  • 4,137
  • 5
  • 38
  • 54
  • 3
    I don't think this is a duplicate of that question. I think he's asking for a way to obtain an object by its variable name. – JeremyP Jun 16 '11 at 14:31
  • Also [Use NSString as object name](http://stackoverflow.com/questions/3684991/use-nsstring-as-object-name) and [Convert an NSString into the name of a constant](http://stackoverflow.com/questions/5542835/convert-a-nsstring-into-the-name-of-a-constant) and [Using a string representing the name of a variable to set the variable](http://stackoverflow.com/questions/5680284/) – jscs Jun 16 '11 at 17:11
  • Take a look to this question : [http://stackoverflow.com/questions/6286549/get-an-ivar-or-property-from-a-nsstring](http://stackoverflow.com/questions/6286549/get-an-ivar-or-property-from-a-nsstring) – klefevre Jun 16 '11 at 14:18

2 Answers2

3

At run time the identifier myVar means nothing, it's replaced by an address in memory. If you want to be able to obtain objects by name, you need to use an NSDictionary or mutable dictionary e.g.

NSDictionary* map = [NSDictionary dictionaryWithObjectsAndKeys: 
                        [[[MyClass alloc] init] autorelease], @"myVar", nil];

Then access as follows:

[map objectForKey: @"myVar"];
JeremyP
  • 84,577
  • 15
  • 123
  • 161
0

If it is an instance variable, just use valueForKey:. If it is a local variable, you are out of luck. If it is a global, you can do it, but it is ugly, slow and beg's the question of "why?!".


You'll have to provide more information as to what you are trying to do. By definition a local variable is only valid within the scope within which it is defined. Given that, it is hard to imagine a situation where you would need to access a local variable symbolically where there isn't also a better/cleaner/easier way.

bbum
  • 162,346
  • 23
  • 271
  • 359