variable variable names?

Discussion in 'iOS Programming' started by thomasjt, Jul 7, 2009.

  1. thomasjt macrumors newbie

    Joined:
    Apr 16, 2009
    #1
    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
     
  2. Guiyon macrumors 6502a

    Joined:
    Mar 19, 2008
    Location:
    North Shore, MA
    #2
    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.
     
  3. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #3
    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.
     
  4. thomasjt thread starter macrumors newbie

    Joined:
    Apr 16, 2009
    #4
    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
     

Share This Page