Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

thomasjt

macrumors newbie
Original poster
Apr 16, 2009
23
0
Hi,

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

Code:
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
 
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.
 
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.
 
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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.