2

I have a variable name referencing question for the Objective C gurus out there.

Lets say I have 6 UILabels on a form, the are setup with properties naming them myLabel1 - myLabel6

I would like to go through a for loop and populate these with something depending on the loop but im unsure how to specifiy the for loops variable and make it part of the labels name.

Here is what I would like to do:

for (int LP = 0; i <5)
{

    labelLP.text = [NSString stringWithFormat:@"My label number:%d", LP};
}

What im not sure of is how to reference the label and append the LP int and use it in my loop. I'm sure there is a way to do this just not sure how.. Anyone??

3 Answers 3

5

you can always take advantage of the dynamic runtime of objective-c:

id var = object_getIvar(self,class_getInstanceVariable([self class], [[NSString stringWithFormat:@"label%d",LP] UTF8String]));

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html

Sign up to request clarification or add additional context in comments.

Comments

2

Whether one likes this approach is a question of style, but here's a way that should work:

for (int LP = 1; i <=6)
{
    NSString *labelName = [NSString stringWithFormat: @"label%d", i];
    UILabel *labelLP = (UILabel*)[self valueForKey: labelName];
    labelLP.text = [NSString stringWithFormat:@"My label number:%d", LP};
}

Comments

1

I don't think you can create variable names on the fly, at least not trivially.

You could always use a switch case inside your loop:

for (int i=0; i<5; i++) {

    switch(i) {

        case 1:
            myLabel1.text = [NSString stringWithFormat:@"My label number: %d", i];
            break;
        case 2:
            myLabel2.text = [NSString stringWithFormat:@"My label number: %d", i];
            break;
        ...
        ...
    }
}

You could also store your labels in an array, and loop through that array.

The important point is not to get fixated about the variable names, but to think about why you need your objects and how to get them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.