开发者

Objective-c create variables in a loop

开发者 https://www.devze.com 2023-03-23 02:01 出处:网络
Is there a way to create variables inside of a loop. Basically something like this, except开发者_Python百科 that the variables variable1, variable2 and variable3 would exist.

Is there a way to create variables inside of a loop. Basically something like this, except开发者_Python百科 that the variables variable1, variable2 and variable3 would exist.

int x;

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


Nope, there isn't.

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 your xs in an NSMutableDictionary, which is comparable to an associative array in other languages.


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


YOu could 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

精彩评论

暂无评论...
验证码 换一张
取 消