View Full Version : increment variable name in a loop?

Feb 4, 2011, 05:25 AM
Um, I haven't been able to figure out how to use variables to name variables.

For example the piece below here, would be so much cleaner inside a for loop.

I want to transform this piece:

cell.textLabel0.text = [localValues objectAtIndex:0];
cell.textLabel1.text = [localValues objectAtIndex:1];
cell.textLabel2.text = [localValues objectAtIndex:2];
cell.textLabel3.text = [localValues objectAtIndex:3];
cell.textLabel4.text = [localValues objectAtIndex:4];
cell.textLabel5.text = [localValues objectAtIndex:5];


for (int i = 0; i < 6; i+=){
cell.textLabel+i<?HowDoIIncrement?>.text = [localValues objectAtIndex:i];

Feb 4, 2011, 07:17 AM
you can't.
the textLabels need to be in an array.

Feb 4, 2011, 09:14 AM
Look up valueForKey:

Feb 4, 2011, 10:10 AM
So, you have a single table cell with six labels in it, is that correct?

Feb 4, 2011, 03:27 PM
So, you have a single table cell with six labels in it, is that correct?

In this case yes.

Phoney, can you give me a bit more than valueForKey - you don't mean a Dictionary?

I don't need to stick the variables in a dictionary or anything, I just want to be able to do like the example. No biggie really, just one of those things in Java that are really handy.

Feb 4, 2011, 05:15 PM
I said look up the method valueForKey: in NSObject.

Feb 4, 2011, 05:18 PM
Look up valueForKey:

That's quite a neat implementation of reflection. Never had a reason to use this yet, but it's nice. Thanks!

Feb 4, 2011, 05:26 PM
The usual reason to use it is to get around Apple's private apis to get/set private ivars ;-) which is illegal of course and you should never do it.

Actually I don't think I've ever used it in a shipping app. It's a little too weird for me.

The kind of thing OP wants to do can be done this way but it's a little too weird for me.

Feb 4, 2011, 05:32 PM
In this case yes.
You might want to consider tagging each of the labels and then using UIView's viewWithTag: instance method.

Feb 5, 2011, 03:12 AM
Ok, I see where you are going with valueForKey. It will actually do the job.

To be honest though the code is a fair bit convoluted so I'm probably better off not looping through. It's just one of those things I suppose, quirks of different languages.

Thanks for entertaining me anyway!

Feb 5, 2011, 06:25 PM
That's what I live for.