2

If I had two variables in Objective C like this where one holds the name of the other as a string

NSInteger result = 4;
NSString * theName = @"result";

How would I best access the first variable using the string instead of a reference to the variable? For instance if I had a lot of variables and would generate the name of the one I need by code I'd need a way to get to the variable using that string.

Rodrigo Guedes
  • 1,169
  • 2
  • 13
  • 27
C.O.
  • 2,281
  • 6
  • 28
  • 51
  • Can we have some more context? You cannot get by with putting things into a NSDictionary, I suppose? And do you need this for properties or variables ? – Thilo Aug 24 '12 at 12:54

2 Answers2

6

Though not directly answering your question, it's possible to access properties (or ivars) of an object by

[object setValue:@"value" forKey:theName]

Similarly, the getter is [object valueForKey:theName] (thanks kevboh!)

user1071136
  • 15,636
  • 4
  • 42
  • 61
  • Similarly, the getter is `[object valueForKey:theName]`. – kevboh Aug 24 '12 at 12:58
  • 1
    Problem is, he needs to get the object itself based on a string :) – Asciiom Aug 24 '12 at 13:04
  • 2
    @JeroenMoons Still, Objective-C code is usually written in the context of a class, and the variables are in fact ivars or properties, in which case my answer solves the problem. – user1071136 Aug 24 '12 at 13:07
  • In that case you could use it yes. Still a rather strange way of doing things :) btw, small syntax error in your code: [object setValue:@"value" forKey:@"theName"]; – Asciiom Aug 24 '12 at 13:11
1

That's not possible in objective-c. Variable names cannot be synthesised by name. The variable name itself doesn't mean anything when running your code, the compiler converts it into a memory address. The name is just a way for the programmer to make writing and reading code easier.

Depends on your exact situation but you probably should be using an NSArray or NSDictionary.

Asciiom
  • 9,867
  • 7
  • 38
  • 57
  • Not me, but possibly because you just say it's not possible, without substantiating your answer. – user1071136 Aug 24 '12 at 13:08
  • I gave some more explanation now, still strange though :) – Asciiom Aug 24 '12 at 13:10
  • Regarding your edited answer - so how come ivars and properties _can_ be accessed like this? maybe variables can also be accessed, somehow? – user1071136 Aug 24 '12 at 13:11
  • I don't know why it is like that, I only know it is. Local variables can't be retrieved based on a string containing its name. Your method works for instance vars but that doesn't make my general remark invalid. – Asciiom Aug 24 '12 at 13:14
  • 1
    I didn't downvote it but you know what I'll vote you back to 0. – C.O. Aug 24 '12 at 13:15
  • Thanks C.O., question was 'can I do this?' and saying no wasn't an option apparently :) – Asciiom Aug 24 '12 at 13:17