Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Load Classes in Objective-C?

Is there a way to #import a class from a string in Objective-C at run time? Any methods that would produce a similar result would also be welcome.

Edit:

I want access to a class whose name I determine at runtime. So something like this:

NSString *className = getClassName();
Class myClass = loadClass(className);
myClass *myVar = [[myClass alloc] init];

Is there any way to do this without putting a static #import directive for myClass at the top of the file?

like image 832
Jacob Lyles Avatar asked Nov 15 '10 19:11

Jacob Lyles


2 Answers

You can use NSClassFromString method. So:

// Creates an instance of an NSObject and stores it in anObject
id anObject = [[NSClassFromString(@"NSObject") alloc] init];

Some more sample code in response to your edit:

NSString* myClassString = getClassName();
// if the class doesn't exist, myClass will be Nil and myVar will be nil
Class* myClass = NSClassFromString(myClassString);
id myVar = [[myClass alloc] init];
like image 116
Jason Coco Avatar answered Sep 19 '22 01:09

Jason Coco


The #import directive does not "import" a class — it inserts the text from the named file into the current file. This obviously isn't useful at runtime after the source has been compiled.

What you want is to create a bundle with the classes and dynamically load the bundle. In order to be able to talk to the classes from the core program, you'll probably want to have some common protocol that bundled classes implement.

like image 24
Chuck Avatar answered Sep 21 '22 01:09

Chuck