String as variable

Discussion in 'Mac Programming' started by forrestgrant, Jul 24, 2008.

  1. forrestgrant macrumors member

    Joined:
    Jun 24, 2008
    #1
    Hello,
    I have some variables defined like so:
    Code:
    #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:

    Code:
    //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!
     
  2. kpua macrumors 6502

    Joined:
    Jul 25, 2006
    #2
    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:

    Code:
    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.
     
  3. Cool6324 macrumors member

    Joined:
    Sep 18, 2007
    Location:
    Raleigh, NC
  4. forrestgrant thread starter macrumors member

    Joined:
    Jun 24, 2008
  5. forrestgrant thread starter macrumors member

    Joined:
    Jun 24, 2008
    #5
    also... I need the keys to be specific words and characters. They cant simply be an array sequence.
     
  6. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #6
    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
     
  7. forrestgrant thread starter macrumors member

    Joined:
    Jun 24, 2008
    #7
    I think that is the answer I needed... thanks!
    (NSMutableDictionary)
     

Share This Page