Dynamically load classes in Objective-C?

Is there a way to #import a class from a string in Objective-C at runtime? Any methods that lead to a similar result will also be welcome.

Edit:

I need access to a class whose name I define at runtime. So something like this:

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

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

+7
dynamic objective-c iphone cocoa
source share
3 answers

The #import directive does not "import" a class - it inserts text from a named file into the current file. This is clearly not useful at runtime after the source has been compiled.

You want to create a package with classes and load the package dynamically . To be able to talk to classes from the main program, you probably want to have a common protocol that is implemented in the kit.

+5
source share

You can use the NSClassFromString method. So:

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

Another example 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]; 
+25
source share

Thanks to Chuck for pointing me to the right path, but the correct answer to this request seems like this is not possible in iOS 4.1, although this is possible with the current Mac OSX SDK using downloadable packages.

0
source share

All Articles