语法帮助 - 变量作为对象名称 [英] Syntax help - Variable as object name
本文介绍了语法帮助 - 变量作为对象名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
根据整数计数创建多个变量
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屋!
查看全文