znerolnoht
znerolnoht

Reputation: 152

Instantiation from a reference to a class

This one's a little difficult to explain. I've got an array of class references. I'd like to instantiate a member of one of the class but I don't want to have use a conditional.

Here's my code that works (below is what I'd like to do):

self.myClasses = [NSMutableArray arrayWithObjects:
                     [MyClassA class],
                     [MyClassB class],
                     [MyClassC class],
                     [MyClassD class],nil];

// later
int indexOfClassThatIWantAMemberOf = 2;

switch (indexOfClassThatIWantAMemberOf) {
                case 0:
                    myObj = [[MyClassA alloc] init];
                    break;
                case 1:
                    myObj = [[MyClassB alloc] init];
                    break;
                case 2:
                    myObj = [[MyClassC alloc] init];
                    break;
                case 3:
                    myObj = [[MyClassD alloc] init];
                    break;

                default:
                    break;
            }

The above works fine but I'd rather have one line of code, something like this:

NSObjet *myOb = [[[self.myClasses objectAtIndex:i] alloc] init];

Anyone know if this is possible? Thanks for the help.

Upvotes: 0

Views: 37

Answers (2)

rmaddy
rmaddy

Reputation: 318924

Try it this way:

self.myClasses = [NSMutableArray arrayWithObjects:
                     [MyClassA class],
                     [MyClassB class],
                     [MyClassC class],
                     [MyClassD class],nil];

// later
NSUInteger indexOfClassThatIWantAMemberOf = 2;
Class class = self.myClasses[indexOfClassThatIWantAMemberOf];
id myObj = [[class alloc] init];

Upvotes: 0

Aaron Wojnowski
Aaron Wojnowski

Reputation: 6480

Have you tried doing what you suggested? It's certainly possible.

NSArray *array = @[[Class1 class], [Class2 class]];
id object = [[array[0] alloc] init];

Upvotes: 1

Related Questions