Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create objective-c class instance by name?

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,

like image 281
Mark Avatar asked Jul 23 '09 19:07

Mark


People also ask

How to create NSObject Class in Objective-C?

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.

Is Objective-C as fast as C?

Objective-C is slightly slower than straight C function calls because of the lookups involved in its dynamic nature.


2 Answers

id object = [[NSClassFromString(@"NameofClass") alloc] init]; 
like image 157
Chris McCall Avatar answered Nov 26 '22 19:11

Chris McCall


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.

like image 33
Simon Woodside Avatar answered Nov 26 '22 20:11

Simon Woodside