与 PHP 的“变量变量"等效的 Objective C [英] Objective C Equivalent of PHP's "Variable Variables"
本文介绍了与 PHP 的“变量变量"等效的 Objective C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 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 的名称构建为字符串,然后使用类似
object_getInstanceVariable()
直接检索它的值(这类似于#3,除非你不t 必须将其声明为@property
).这过于复杂,而且通常比您实际需要的锤子大得多. - 如果您正在处理视图,您可以为每个视图分配一个唯一的标签,然后通过
[superview viewWithTag:aTag]
检索它.我不建议使用这种方法.
- 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.
这篇关于与 PHP 的“变量变量"等效的 Objective C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文