0

I want to get property name by self.label1, self.label2, self.label3 etc. Do you know how to convert NSString to some method like JS or Ruby.

my header is

@property(nonatomic,strong)CCLabelTTF *label1;
@property(nonatomic,strong)CCLabelTTf *label2;...

implementations

for (int i = 0; i < 10; ){

  NSString *str = [NSString stringWithFormat:@"self.label%i",i];
  // convert str to property
  converted_str = [CCLabelTTF labelWithString:%@"hello  below style is  not good...

I want to avoid this style...

for(int i  = 0 ;i < 10;){
   if (i == 0){
   self.label1 = ...
   }else if(i == 1){
   self.label  = ...
}

Do you have any idea? Thanks in advance.

hol
  • 8,255
  • 5
  • 33
  • 59
nobinobiru
  • 792
  • 12
  • 28
  • You could use an array, or KVC, but that's about it. – Richard J. Ross III Aug 23 '12 at 20:16
  • possible duplicate of [ObjC equivalent of PHP's "Variable Variables"](http://stackoverflow.com/questions/2283374/objective-c-equivalent-of-phps-variable-variables), [Create multiple variables based on an int count](http://stackoverflow.com/questions/2231783/create-multiple-variables-based-on-an-int-count/), [Syntax help: variable as object name](http://stackoverflow.com/questions/7940809/syntax-help-variable-as-object-name) – jscs Aug 23 '12 at 20:26

4 Answers4

4

Why not put your labels into an array like this:

NSArray *myLabels = @[self.label1, self.label2...];

Then you could:

for (CCLabelTTF *label in myLabels) {
    // Do something with the label
}

Alternatively you could make use of KVC.

for (int i = 1; i <= 10; i++) {
    NSString *labelName = [[NSString alloc] initWithFormat:@"label%d", i];
    CCLabelTTF *label = [self valueForKey:labelName];
    // Do something with the label
}
DrummerB
  • 39,814
  • 12
  • 105
  • 142
2

Try using KVC:

NSString *keyPath = [NSString stringWithFormat:@"label%i", labelNumber];

id value = [CCLabelTTF ....];

[self setValue:value forKey:keyPath]; // use KVC to set the value for you
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
0

You can do this with Key-Value Coding, but it really sounds like what you want is to use an array. If the reason you aren't using an array is because these are outlets that you need to hook up, you can just declare an array as an IBOutletCollection and it will work.

Chuck
  • 234,037
  • 30
  • 302
  • 389
0

well, the more primitive form of the KVC angle would be:

SEL sel = NSSelectorFromString(propertyName);
id leProperty = [object performSelector:sel];

however, KVC is more thorough, and if you mis-type using this method, an exception will be thrown. as well, performSelector: is not very ARC-friendly.

if you want to drop lower than this, you can always do this using the objc runtime.

justin
  • 104,054
  • 14
  • 179
  • 226