Can I reference a variable with a string and int?

Is it possible to reference a variable with a string and an int like:

    int number1;

    int j = 1;

    @"number%i", j = 3; //Hope this makes sense..


The above code is giving me warnings and doesn't work how it can be done.

I've also tried this, but it doesn't work (for obvious reasons):

    int j = 1;

    NSString *refString = [NSString stringWithFormat:@"number%i", j];

    refString = 3;


I'm really struggling with this, I know how to do it in Javascript but not in Obj-C, is it possible?


source to share

2 answers

This is anti-pattern I call "Poor Man". The best way to do this is to use the correct collection, such as an array, instead of a bunch of variables that are secretly linked. Done right, array code will generally be much shorter and cleaner too.



From which I can conclude that you are trying to set / get different variables based on value j


You can use a dictionary for this purpose:

NSMutableDictionary *numbers = [NSMutableDictionary dictionary];
int j = 1;
[numbers setObject:[NSNumber numberWithInt:3] forKey:[NSNumber numberWithInt:j]];


And then, to get:

[[numbers objectForKey:[NSNumber numberWithInt:j]] intValue];


It's a bit verbose, but you can simplify it by creating a small class.



All Articles