0

I've an array which holds different kinds of objects: UIButtons, UILabels, UITableViews, etc.

Is there any way that I can dynamically create these objects while looping through the array without using if/else conditions like below:

for (NSObject *obj in objectsArray)
{
    if ([obj isKindOfClass:[UIButton class]]) 
    {
         UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
         [self.view addSubview:btn];
    }
    else if ([obj isKindOfClass:[UILabel class]]) 
    {
        UILabel *lbl = (UILabel*)obj;
        [self.view addSubview:lbl];
    }
}

Can we create objects like UIButton *btn or UILabel *lbl using reflection or something dynamically?

jscs
  • 63,694
  • 13
  • 151
  • 195

1 Answers1

0

you could either do

for (Class _class in classArray) {
    id object = [[_class alloc] init];
}

or

for (NSString *className in classNameArray) {
    id object = [[NSClassFromString(className) alloc] init];
}

so you dont need Instances for the class-reference.

Jonathan Cichon
  • 4,396
  • 16
  • 19
  • This assumes that the objects in the array are either strings representing class objects, or the classes themselves; from OP's code, that is not the case: the array contains _instances_. – jscs Jan 24 '13 at 19:50