Reputation: 85
I want to set the name of a variable to the value of another variable are there any other ways to do this because I don't think this is the way.
NSString *myint = @"a";
NSString *([NSString stringWithFormat:@"%@", myint]) = @"something";
NSLog(@"%@", a);
Upvotes: 2
Views: 538
Reputation: 124997
No, you can't do that. Once your code is compiled, your variables don't really have names -- just locations. The names you see in the debugger are provided by a symbol file which the debugger uses to map locations to names.
Key-value coding could help, depending on what you're really trying to accomplish. With KVC, you use key names to refer to values rather than accessing variables, much as you do with a dictionary. For example, if you have an object with properties foo
and bar
, you can then do something like this:
NSString *key = @"foo";
[myObject setValue:@(5) forKey:key];
You could even override -setValue:forKey:
so that it accepts any key and remembers the value (which is exactly what a dictionary does).
You can go in the other direction (set a variable to the name of another variable) using the stringification operator, but it's kinda hacky and not usually all that useful. In a nutshell, macro parameters prefixed with a # are used as literal strings instead of being evaluated. So you'd create a macro like this:
#define string(x) #x
and then you'd use it somewhere in your code like this:
int foo = 5;
NSLog("The name of the variable is %s and its value is %d.", string(foo), foo);
with the following result:
The name of the variable is foo and its value is 5.
Upvotes: 1
Reputation: 183
I agree with Paulw11. You could define a NSMutableDictionary to hold all your variables by key. I don't think there is any way the compiler can use a handle determined at runtime. But you can achieve the same affect.
So say, for instance, that both the variable handle and value were NSString
, then you could do something like this.
NSMutableDictionary *myObjects = [[NSMutableDictionary dictionary] init];
NSString variableName = @"myString";
[myObjects setObject @"Variable value" forKey: variableName];
NSLog("Variable %@ has value %@.", variableName, [myObjects objectForKey: variableName]);
Upvotes: 0