1

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

int x;

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

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.