Can this be replaced by a cycle?

Animal* leon = [[Leon alloc]init]; Animal* zebra = [[Zebra alloc]init]; Animal* kenguru = [[Kenguru alloc]init]; Animal* mouse = [[Mouse alloc]init]; Animal* penguin = [[Penguin alloc]init]; 
  • Probably yes, if we put class identifiers into an array, and then element.instanceOf() over the elements of the array and do something like element.instanceOf() on each (somehow in Java, but the same syntax should be in Obj-C). But why? You will make the code much less understandable. - Nick Volynkin
  • In order not to manually create and initialize> 100 instances, but to run it out in a loop. - foggie
  • do you have there> 100 copies of different classes like Leon, Zebra, etc.? Or am I just misunderstood the syntax? - Nick Volynkin
  • That's right, different classes. - foggie
  • if you have them there for a hundred, why do you need to have separate variables for them, isn't it easier to put them into an array? - Max Mikheyenko

1 answer 1

If you store all the objects in the array is suitable, you can do so

 NSArray *listOfAnimals = @[@"Zebra", @"Penguin"]; NSMutableArray *listOfAnimalInstances = [NSMutableArray new]; for(int i = 0; i<listOfAnimals.count; i++) { [listOfAnimalInstances addObject:[NSClassFromString(listOfAnimals[i]) new]]; } 
  • Thank! Exactly what is needed! - foggie