-5

I have some object with 18 properties (number of properties in that object is static and do not change over the time). Each property stores some information. I need to create a UILabels in cycle (for, foreach, etc.) and set current object.property to current label. How I can do that?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Sergey Krasiuk
  • 198
  • 2
  • 9

1 Answers1

2

You may use the code like that:

id object; // your object
NSArray *properties = @[ @"prop1", @"prop2", ... ]; // your properties
[properties enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, idx * 30, 0, 30)]; // or set your custom frame
    label.text = [NSString stringWithFormat:@"%@", [object valueForKey:obj]];
    [label sizeToFit];
    [self.view addSubview:label]; // add to some superview
}];

You also can get all of your properties using Objective-C Runtime without having prepopulated properties array, please refer here to SO

Notice that if some of your properties are scalar types this code will crash. So you probably need some type check here

Community
  • 1
  • 1
Azat
  • 6,745
  • 5
  • 31
  • 48