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


- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01