【问题标题】:Syntax help - Variable as object name [duplicate]语法帮助 - 作为对象名称的变量 [重复]
【发布时间】:2011-12-17 22:55:34
【问题描述】:

可能重复:
create multiple variables based on an int count
Objective C Equivalent of PHP's “Variable Variables”

如何使用变量作为名称来创建和引用对象?

例子-

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

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

【问题讨论】:

标签: iphone objective-c ios xcode


【解决方案1】:

在 Objective-C 语言中没有这样的东西,而且通常它不会是一种非常实用的引用数据的方式(如果你打错了一个字符串怎么办?编译器将无法捕获它)。我不会去猜测你真正想要做什么(这将取决于你的应用程序这部分的目标),但你可以使用NSMutableDictionary 来获得类似的效果:

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];
}

然后再次取回值:

NSValue *value = [dict objectForKey:@"myRectNum & 5"];
CGRect bounds = [value CGRectValue];
NSLog(@"height = %f", bounds.size.height);

【讨论】:

  • 谢谢,我正在使用这种方法来处理简单的变量,但是可以存储路径吗? myPath = CGPathCreateMutable();
  • 是的,您可以将 CGPathRef 存储在字典中。如果您使用 ARC,则需要查看 __bridge 等限定符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-23
  • 2013-06-19
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 2013-12-03
  • 1970-01-01
相关资源
最近更新 更多