将NSArray对象移动到UITextFields的最有效方法是什么?

时间:2013-09-16 20:26:55

标签: objective-c nsarray

我有一些代码,其中可能有或没有数组中的对象...这是我正在处理的代码:

        oServices1.text = CustomServicesArray[0];
        oServices2.text = CustomServicesArray[1];
        oServices3.text = CustomServicesArray[2];
        oServices4.text = CustomServicesArray[3];
        oServices5.text = CustomServicesArray[4];
        oServices6.text = CustomServicesArray[5];
        oServices7.text = CustomServicesArray[6];
        oServices8.text = CustomServicesArray[7];
        oServices9.text = CustomServicesArray[8];
        oServices10.text = CustomServicesArray[9];
        oServices11.text = CustomServicesArray[10];
        oServices12.text = CustomServicesArray[11];
        oServices13.text = CustomServicesArray[12];
        oServices14.text = CustomServicesArray[13];
        oServices15.text = CustomServicesArray[14];
        oServices16.text = CustomServicesArray[15];
        oServices17.text = CustomServicesArray[16];
        oServices18.text = CustomServicesArray[17];
        oServices19.text = CustomServicesArray[18];
        oServices20.text = CustomServicesArray[19];
        oServices21.text = CustomServicesArray[20];
        oServices22.text = CustomServicesArray[21];
        oServices23.text = CustomServicesArray[22];

不是检查每个数组对象是否为nil,有没有办法可以将oServices * xx * .text UIFields放到某种数组中,这样我就可以使用循环了?

3 个答案:

答案 0 :(得分:2)

你知道反身性吗?使用KVC,您可以节省大量代码和时间:

for(int i=1; i<=23; i++) {
    NSString* key= [NSString stringWithFormat: @"oServices%d"i];
    // Remember that variables should start with a lowercase letter
    [[self valueForKey: key] setText: customServicesArray[i-1] ]; 
}

但是如果你不想在storyboard / xib文件中绑定所有这些变量(即使这可能太多了),只需按照你想要的顺序设置每个文本字段的标记(从1开始),这样你可以使用viewWithTag来取回它们:

// From the UIViewController
for(int i=1; i<=23; i++) {  // Consider defining a constant instead of 23
    [[self.view viewWithTag: i] setText: customServicesArray[i-1] ];
}

我认为最后一个解决方案更好,因为你避免绑定这么多变量。

答案 1 :(得分:0)

您可以使用OutletCollection来保存oServices并在其上循环。但请注意,插座集合未进行排序,因此您需要事先对其进行排序(例如,在标签条件或位置上)。

如需订购,请参阅this question

答案 2 :(得分:0)

将UITextFields的tag属性设置为数组中对应的序号。 tag的默认值为0,因此如果UITextFields的父视图中有其他视图,则可能需要将tag属性设置为ordinal + 1。在文本字段的父视图中,您可以使用viewWithTag:方法检索相应的UITextField。

相关问题