7

Possible Duplicate:
create multiple variables based on an int count
Objective C Equivalent of PHP's “Variable Variables”

How would I create and reference an object using a variable as it's name?

Example -

    for (int i=1; i<7; i++) {
       CGRect ("myRectNum & i") = myImageView.bounds; 
    }

 ("myRectNum & 5").height  etc ..
1

1 Answer 1

2

There isn't anything like this in the Objective-C language, and in general it's not going to be a very practical way of referring to data (what if you typo a string? the compiler won't be able to catch it). I won't get into second-guessing what you actually want to do (that would depend on the goal of this part of your application), but you can use an NSMutableDictionary to get a similar effect:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (int i = 0; i < 7; i++)
{
    NSString *key = [NSString stringWithFormat:@"myRectNum & %d", i];
    NSValue *value = [NSValue valueWithCGRect:myImageView.bounds];
    [dict setObject:value forKey:key];
}

Then to fetch the values back out again:

NSValue *value = [dict objectForKey:@"myRectNum & 5"];
CGRect bounds = [value CGRectValue];
NSLog(@"height = %f", bounds.size.height);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I am using this method for simple variables but is it possible to store a path? myPath = CGPathCreateMutable();
Yes, you can store a CGPathRef in a dictionary. If you are using ARC you will need to look at the __bridge, etc. qualifiers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.