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,
Creating a Custom ClassGo ahead an choose “Objective-C class” and hit Next. For the class name, enter “Person.” Make it a subclass of NSObject. NSObject is the base class for all objects in Apple's developer environment. It provides basic properties and functions for memory management and allocation.
Objective-C is slightly slower than straight C function calls because of the lookups involved in its dynamic nature.
id object = [[NSClassFromString(@"NameofClass") alloc] init];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With