运行时的 Objective-C 变量动态命名/引用 [英] Objective-C variable dynamic naming/referencing at runtime

查看:31
本文介绍了运行时的 Objective-C 变量动态命名/引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 Objective C 专家的变量名引用问题.

I have a variable name referencing question for the Objective C gurus out there.

假设我在一个表单上有 6 个 UILabel,它们的设置属性将它们命名为 myLabel1 - myLabel6

Lets say I have 6 UILabels on a form, the are setup with properties naming them myLabel1 - myLabel6

我想通过一个 for 循环并根据循环用一些东西填充它们,但我不确定如何指定 for 循环变量并使其成为标签名称的一部分.

I would like to go through a for loop and populate these with something depending on the loop but im unsure how to specifiy the for loops variable and make it part of the labels name.

这是我想要做的:

for (int LP = 0; i <5)
{

    labelLP.text = [NSString stringWithFormat:@"My label number:%d", LP};
}

我不确定的是如何引用标签并附加 LP int 并在我的循环中使用它.我确定有办法做到这一点,只是不知道如何..有人吗??

What im not sure of is how to reference the label and append the LP int and use it in my loop. I'm sure there is a way to do this just not sure how.. Anyone??

推荐答案

我认为你不能即时创建变量名,至少不是微不足道的.

I don't think you can create variable names on the fly, at least not trivially.

你总是可以在循环中使用 switch case:

You could always use a switch case inside your loop:

for (int i=0; i<5; i++) {

    switch(i) {

        case 1:
            myLabel1.text = [NSString stringWithFormat:@"My label number: %d", i];
            break;
        case 2:
            myLabel2.text = [NSString stringWithFormat:@"My label number: %d", i];
            break;
        ...
        ...
    }
}

您也可以将标签存储在一个数组中,然后遍历该数组.

You could also store your labels in an array, and loop through that array.

重要的一点不是执着于变量名,而是考虑为什么需要对象以及如何获取它们.

The important point is not to get fixated about the variable names, but to think about why you need your objects and how to get them.

这篇关于运行时的 Objective-C 变量动态命名/引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆