Objective-c create variables in a loop
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 to share
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 to share
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 to share