Syntax help - Variable as object name [duplicate]

2019-01-01 02:46发布

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条回答
永恒的永恒
2楼-- · 2019-01-01 03:09

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);
查看更多
登录 后发表回答