Is it possible to create an instance of a class by name? Something like:
NSString* className = @\"Car\";
id* p = [Magic createClassByName:className];
[p turn
NSClassFromString()
runs the risk of mistyping the class name or otherwise using a class that doesn't exist. You won't find out until runtime if you make that error. Instead, if you use the built-in objective-c type of Class
to create a variable, then the compiler will verify that the class exists.
For example, in your .h
:
@property Class NameOfClass;
and then in your .m
:
id object = [[NameOfClass alloc] init];
If you mistyped the class name or if it doesn't exist, you'll get an error at compile time. Also I think this is cleaner code.