PDA

View Full Version : String as variable




forrestgrant
Jul 24, 2008, 10:16 AM
Hello,
I have some variables defined like so:

#define var_a 23.4323
#define var_b 4.24
#define var_c 78.325
#define var_d 1.01


Now I can easily access these variables using their names. However I am looping through and array, the keys of which are a, b, c, d. Therefor, I would like something to the effect of:


//array loop start, loop keys a, b, c, d
NSLog(var_[append current key]);
//array loop end


So that the Log output would look like:
23.4323
4.24
78.325
1.01

Thanks!



kpua
Jul 24, 2008, 10:33 AM
First of all, those aren't variables. They're macros. #define macros are resolved at compile time, so there's no way to do this with the approach you're using.

I think you want to use an array. Try something like this:


float arr[4] = { 23.4323, 4.24, 78.325, 1.01 };

int i;
for(i = 0; i < 4; i++) {
NSLog(@"%f", arr[i]);
}


If you need to access these values by name, use a dictionary or a hash.

Cool6324
Jul 24, 2008, 10:39 AM
Never mind, I was wrong....

forrestgrant
Jul 24, 2008, 10:52 AM
wait... who was wrong about what?

forrestgrant
Jul 24, 2008, 11:07 AM
also... I need the keys to be specific words and characters. They cant simply be an array sequence.

lee1210
Jul 24, 2008, 12:06 PM
You might want to try to explain what you are trying to achieve and why. We may be able to assist you further with more information. For what it's worth, I don't think Objective-C is able to compose a variable name from a string then access the value of the variable. Someone might need to correct me on this.

If you really need to use names to access information you should look in to using an NSMutableDictionary. Your key could be an NSString that you compose, and the value you could be an NSNumber that is wrapping a float.

-Lee

forrestgrant
Jul 24, 2008, 12:58 PM
I think that is the answer I needed... thanks!
(NSMutableDictionary)