语法帮助 - 作为对象名称的变量 [英] Syntax help - Variable as object name

查看:33
本文介绍了语法帮助 - 作为对象名称的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
根据整数计数创建多个变量
Objective C 等价于 PHP 的“变量变量”

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

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

例子-

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

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

推荐答案

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

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

然后再次取回值:

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

这篇关于语法帮助 - 作为对象名称的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆