Objective-c create variables in a loop

Is there any way to create variables inside the loop. Basically something like this, except that the variables variable1, variable2 and variable3 will exist.

int x;

for (x = 1; x < 4; x++) {
   int variable[x]; 
   variable[x] = x;
}

      

+1


source to share


3 answers


No no.

But you can do something like this:



NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
for (int i = 0; i < 4; i++) {
    [dictionary setObject:[NSNumber numberWithInt:i] forKey:[NSString stringWithFormat:@"%i", i]];
}

      

This will save yours x

in NSMutableDictionary

, which is comparable to an associative array in other languages.

+3


source


You are thinking wrongly about variable names. What you are looking for is a data structure like an index based array or dictionary ( hash table ) to hold these values.



0


source


You can use an array and set each value however you like. in your example you have a fixed for loop, so you can define an array of 4 and iterate.

code:

NSMutableArray *myArray = [NSMutableArray arrayWithCapacity:4];

for (int x=0; x<4; x++)
{
    [myArray addObject:x]; 
}
//you now have an array of 4 int like this: [1,2,3,4]

      

0


source







All Articles