views:

37

answers:

2

Let's say I've got several UILabels which have been set up in IB and connected to IBOulets in code (label1, label2, label3, label4)

How would I create these variable names within code, so that I could change the text of each one in a loop, where the labels are taken from a NSArray.

Here's the pseudo-code:

labelArray = [NSArray arrayWithObjects:@"this", @"array", @"has", @"a", @"random", @"amount", @"of", @"items", nil];
for (int i = 0; i < [labelArray count]; i++) 
{
    // labelx is the constructed name of the IBOutlet
    lablex.text = [labelArray objectAtIndex:i];

}

How do I construct 'labelx' above? Could this be done using Blocks?

+2  A: 

You would have to initialize the array at some place, using

labelArray = [NSArray arrayWithObjects:@"this", @"array", @"has", nil];
uiLabelArray = [NSArray arrayWithObjects:label1,label2,label3,nil];

then

for (int i = 0; i < [uiLabelArray count]; i++) 
{
    [uiLabelArray objectAtIndex:i].text = [labelArray objectAtIndex:i];
}
mvds
I already have a labelArray. The issue is turning that array into text in the UILabels within a loop.
cannyboy
Make 2 arrays then. see my updated answer.
mvds
+2  A: 

You can use key value coding (KVC). It would look something like:

[[self valueForKey:[NSString stringWithFormat:@"label%d", i]] setText:[labelArray objectAtIndex:i]];

More info can be found here

Elfred
Ewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww.
tc.