Question

I have twelve text fields as you can see below:

IBOutlet UITextField *ce_1;
IBOutlet UITextField *ce_2;
IBOutlet UITextField *ce_3;
....
IBOutlet UITextField *ce_12;

All I have to do is to set an existing object in an array in each of the variables that are responsible for the text fields, I'm currently doing as follows:

ce_1.text = myArray[1];
ce_2.text = myArray[2];
ce_3.text = myArray[3];
....
ce_12.text = myArray[12];

Not to be writing a lot, I thought I'd put this in an automated way within a loop as follows:

for(i=1;i<13;i++){
ce_[i].text = myArray[i];
}

But this command does not work the way I expected, so I would like your help to try to solve my idea and put it into practice, is there any way of doing this?

Was it helpful?

Solution 3

You can use IBOutletCollection. You can also use key-value coding:

for(NSUInteger i = 0; i < 13; i++)
{
    [[self valueForKey:[NSString stringWithFormat:@"ce_%u", i]] setText: myArray[i]];
}

This will give you what you want.

OTHER TIPS

Research and start using IBOutletCollection. It will give you an array of text fields that you can build in your storyboard XIB.

Note that you may need to consider the order of the array, and that you might want to sort it (possibly based on the tag of each view).

Technically, you could use string formats and KVC to do what you're currently trying to but it is far from ideal.

You can't just replace ce_1 ce_2 ce_3 with ce_[i] it doesn't work that way. You can only use [number] with an nsarray variable (or decendents).

for example:

NSArray* myArray = @[@1];
NSLog(@"%@", myArray[0]);

You might want to look into IBOutletCollection in order to achieve something similar to what you're looking for.

However, contrary to other answers here IBOutletCollection are ordered by how you link them in the interface builder.

Refer to this for IBOutletCollections: How can I use IBOutletCollection to connect multiple UIImageViews to the same outlet?

The way I like to handle these situations is creating a temporary array containing all the text fields:

NSArray *allFields = @[_ce_1, _ce_2, _ce_3, ...];
NSInteger i = 0;
for (UITextField *tf in allFields)
{
    tf.text = myArray[i];
    i++
}

IBOutletCollection also work but sometimes it gets hard to figure out when you come back to your project which label is #3 or #5 and such... I find this works better for me usually :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top