目标C等同于PHP的“变量" [英] Objective C Equivalent of PHP's "Variable Variables"
本文介绍了目标C等同于PHP的“变量"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在PHP和JavaScript中,您可以通过将另一个变量用作其名称的一部分来动态使用该变量.我不想使用数组作为解决方案的一部分.可以在目标C中实现吗?我想做这样的事情:
In PHP and in JavaScript you can dynamically use a variable by using another variable as part of its name. I do not want to use an array as part of the solution. Can this be achieved in Objective C? I'd like to do something like this:
for (int i=1; i<6; i++) {
if([appRecord.answer(i) length] != 0){
self.textView.answer(i)ViewSingle.text = appRecord.answer(i);
}
}
推荐答案
简短答案:否.
长答案:有点.
- 您可以使用数组,将变量存储在其中,然后对其进行索引.
- 像#1一样,如果您的对象实际上是UI元素,并且您不想要一堆
IBOutlets
,请改用IBOutletCollection
. - 您可以使用字典,将变量存储为值,然后按键查找它们.
- 您可以将所有变量声明为
@property
,然后使用[self valueForKey:]
来按名称查找它们. - 您可以将ivar的名称构建为字符串,然后使用类似
- You can use an array, store your variables in there, and index into it.
- Like #1, if your objects are actually UI elements and you don't want a whole bunch of
IBOutlets
, then use anIBOutletCollection
instead. - You can use a dictionary, store your variables as values, and look them up by key.
- You can declare all your variables as
@property
, and then use[self valueForKey:]
to look them up by name. - You can build the name of the ivar as a string, and then use something like
object_getInstanceVariable()
to retrieve it's value directly (this is similar to #3, except you don't have to declare it as an@property
). This is excessively complicated and is usually a much bigger hammer than you'll actually need. - If you're dealing with views, you can assign each view a unique tag and then retrieve it via
[superview viewWithTag:aTag]
. I do not recommend using this approach.
请注意,这仅适用于实例变量.这不适用于全局/静态变量.
Note that this only works with instance variables. This does not work with global/static variables.
这篇关于目标C等同于PHP的“变量"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文