access objective-c object by string name or variable

前端 未结 3 1113
北荒
北荒 2020-12-12 03:08

i have been looking around and haven\'t quite found anything on doing this and am not sure if its even possible, but this is what i am trying to achieve. please note, i am g

相关标签:
3条回答
  • 2020-12-12 03:24

    sorry guys & gals, i wound up figuring this out. the "setValue:forKeyPath:" turned out to be what i needed. so for an example...

    example.h

    @property (strong, nonatomic) UILabel *label1;
    @property (strong, nonatomic) UILabel *label2;
    @property (strong, nonatomic) UILabel *label3;
    

    example.m

    @synthesize label1, label2, label3;
    
    - (void)someMethod:(int)labelVarInt {
    
    [self setValue:[NSString stringWithFormat:@"This is Label %i", labelVarInt] forKeyPath:[NSString stringWithFormat:@"label%i.text", labelVarInt]];
    
    }
    

    hope this helps anyone else who is needing to do anything similar.

    0 讨论(0)
  • 2020-12-12 03:37

    If the case is simply indexed strings, you should probably use an array, otherwise you are looking for introspection (take a look at this question).

    0 讨论(0)
  • 2020-12-12 03:49

    I think you need to store the labels in an NSArray, then you could access the labels by index.

    Another approach is getting the labels using KVC.

    0 讨论(0)
提交回复
热议问题