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 ..
Community
  • 1
  • 1
user973984
  • 2,804
  • 2
  • 15
  • 13
  • possible duplicate of [create multiple variables based on an int count](http://stackoverflow.com/questions/2231783/create-multiple-variables-based-on-an-int-count) and http://stackoverflow.com/questions/2283374/, among others. – jscs Oct 29 '11 at 19:03

1 Answers1

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);
Adam Preble
  • 2,162
  • 17
  • 28
  • Thanks, I am using this method for simple variables but is it possible to store a path? myPath = CGPathCreateMutable(); – user973984 Oct 29 '11 at 18:43
  • Yes, you can store a CGPathRef in a dictionary. If you are using ARC you will need to look at the __bridge, etc. qualifiers. – Adam Preble Oct 29 '11 at 23:12