PDA

View Full Version : variable variable names?




thomasjt
Jul 7, 2009, 11:29 PM
Hi,

Say that I have three variables, var1, var2, and var3, and I want to do something like this:

for (int i = 0; i < 2; i++) {

var[i] = i;

}



When I try to do this it says that 'var' is undeclared - I get why it's not working. My question is, is there any way to refer to a variable this way - where part of the variable name is filled in at runtime with another variable?

Cheers,

Tom



Guiyon
Jul 7, 2009, 11:55 PM
No, at least not without involving some form of reflection for languages that support it (ObjC, Java, Ruby, etc). Your best bet would be to use a static or dynamically allocated array that you fill in as needed.

PhoneyDeveloper
Jul 8, 2009, 11:17 AM
It is possible to set the values of ivars by name using Key-Value Coding (KVC). However for the example you showed an array would seem to make more sense.

thomasjt
Jul 8, 2009, 08:03 PM
Thank you both for your replies, that's very handy. I ended up using an array as you suggested. But, I will check out this KVC stuff.

Thanks!

Tom