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);
这篇关于语法帮助 - 作为对象名称的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:语法帮助 - 作为对象名称的变量


基础教程推荐
- iOS4 创建后台定时器 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01