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 wa开发者_开发技巧nt 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.
Thanks to Chuck for pointing me on the right path, but the correct answer for this query seems to be that it is impossible on iOS 4.1, though it is possible with the current Mac OSX SDK using loadable bundles.
精彩评论