views:

2744

answers:

2

Duplicate: http://stackoverflow.com/questions/1034350/dynamic-class-creation-in-objective-c/1034368#1034368

Is it possible to create an instance of a class by name? Something like:

NSString* className = @"Car";
id* p = [Magic createClassByName:className];
[p turnOnEngine];

I don't know if this is possible in objective-c but seems like it would be,

Thanks

+14  A: 
id object = [[NSClassFromString(@"NameofClass") alloc] init];
Chris McCall
A: 

As an alternative you can also consider is instead of strings use the type Class. For example, if you have a in your .h:

@property Class classToUseToCreateNewObjects;

then in your .m you could do:

id myGreatObject = [[classToUseToCreateNewObjects alloc] init];

Compared to strings it's a bit pithier, and you avoid typing errors.

sbwoodside