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 x
s 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]
精彩评论