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?
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];
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.
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