views:

815

answers:

3

Ok I have 8 labels and I want to loop through them but am having no luck.

This is what I have tried.

for (int i; i = 0; i < 10; i++)
{
  double va = [varible1.text doubleValue] + i;
  int j = 0 + I 

  label(j).text= [[NSString alloc]initWithFormat:@"%2.1f", va];
}

This errors out. My labels are named like this label0, label1, label2

Any help would be appreciated.

+3  A: 

label(j) is NOT equivalent to label0, label1, etc.

You should create an NSArray of labels, then you can access them with [arrayOfLabels objectAtIndex:j]. If you're not sure what this means, please read the documentation about NSArray...

squelart
+2  A: 

You should maybe add all your labels to a C array, probably in -viewDidLoad

UILabel* labels[] = { label0, label1, label2, ... };

(not entirely sure about the syntax) and then access them like

labels[i].text = ...

By the way, I think you're leaking memory here:

labels[i].text = [[NSString alloc]initWithFormat:@"%2.1f", va];

initWithFormat: will return a string with a retain count of 1. labels[i].text will retain that value again. You should release the string after setting the label's text. I'd probably just autorelease it here:

labels[i].text = [[[NSString alloc]initWithFormat:@"%2.1f", va] autorelease];

or use stringWithFormat (which returns an autoreleased string):

labels[i].text = [NSString stringWithFormat:@"%2.1f", va];
Thomas Müller
Worked great. Thank you.
New to iPhone
A: 

If you cannot or do not want to put your labels in an array, you could iterate through the UIViews using the tag field as an index. You store the index numbers in them (either through IB or programatically) and then get each label using: (UIView *)viewWithTag:(NSInteger)tag.

See below (set theView to the view your labels reside in):

for (int i; i = 0; i < 10; i++)
{
  double va = [varible1.text doubleValue] + i;

  UILabel * label = [theView viewWithTag: i];
  label.text= [[NSString alloc]initWithFormat:@"%2.1f", va];
}
mahboudz