Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string ("MyExampleClass") into a class name (MyExampleClass)

I want to convert a string to a class name. Imagine that I have a string, which changes, containing a class name, for example, the string "MyExampleClass". Now, I want to create an object of the class MyExampleClass. I have to get the class name from the string. I want to do something like the following. (Consider the code just as a sketch.)

NSString *classNameStr = "MyExampleClass";
id theClass = [UIClass classFromString:classNameStr];
theClass *myObject = [[theClass alloc] init];

What is the right way to do this?

like image 340
EmptyStack Avatar asked Jan 11 '11 05:01

EmptyStack


3 Answers

Here's what you'd want:

Class theClass = NSClassFromString(classNameStr); id myObject = [[theClass alloc] init]; 

Note that you can't use theClass as a type name (i.e. theClass *myObject). You'll have to use id for that.

like image 76
Alex Avatar answered Oct 13 '22 00:10

Alex


You want NSClassFromString:

NSString *classNameStr = @"MyExampleClass";
Class theClass = NSClassFromString(classNameStr);
id myObject = [[theClass alloc] init];

You can also use the objc runtime interfaces (e.g. objc_getClass(const char* name), objc_lookUpClass(const char* name)). The former will not load a class. The latter will. That option could be a good thing in some cases.

like image 40
justin Avatar answered Oct 12 '22 22:10

justin


id a = [[NSClassFromString(@"MyExampleClass") alloc] init];

use this one this will give you what you want.

like image 31
Ishu Avatar answered Oct 12 '22 23:10

Ishu