Creating an Object from a Dynamic Object

A quick question for you. I want to be able to instantiate an object. The type of an object is based on a string.

In php you can just replace the class name with a string, but I doubt it is easy in Objective c.

NSString * className;
id theObject;
className = @"TestObject";
theObject = [[className alloc] init];

here is the breakdown of how it might look. I want to try to avoid using the style description of the giant case.

Can a selector system be used for this?

any ideas?

Greetings

+3
source share
2 answers

You can get the class by its name using one of the following obj-c runtime functions (you may need to import the header:

id objc_lookUpClass(const char *name)
id objc_getClass(const char *name)

So your code might look like (not tested it):

NSString * className = @"TestObject";
id theObject = nil;
Class myClass = objc_lookUpClass([className UTF8String]);
if (myClass)
   theObject = [[myClass alloc] init];
+6

Class NSClassFromString()

Class c = NSClassFromString(@"ClassName");
id obj = [[c alloc] init];
+30

All Articles