Create a class at runtime - Why do NSClassFromString AND objc_getclass return nil?
iphone, runtime
Solution
I ran into this same problem. In my case I had code which was looking up the class using
Class aClass = objc_getClass("Foo");
Which worked when the Foo class was in the same project bundle as my AppDelegate.
As part of refactoring the code, I moved the Foo class and associated model classes out of the AppDelegate project into a common static lib project that would be easier to test and reuse.
When I moved the Foo class into libFooBar the objc_getClass("Foo") now returned nil instead of the Foo class.
To solve this, I put in call to the class I am interested in so that the classes from libFooBar are registered with the Objective-C runtime. I did this like so:
Foo* foo = [[Foo alloc] init];
[foo release];
Class aClass = objc_getClass("Foo");
Now the objc_getClass("Foo") returns the Foo class again instead of nil.
I can only assume that the static library classes are not registered until a call to one of the classes in the static library is made.
Problem
I've tried using both: ``` NSClassFromString and objc_getclass ``` to return a class, so I can create it at runtime, but both functions return nil for some classes, for example "TestClass". Note that NSClassFromString works for me for 99% of classes. If I add ``` [TestClass class]; ``` before I call NSStringFromClass or objc_getclass it, it works. and if I try to just create the class using a class reference, i.e.: ``` [TestClass alloc]; ``` it works too. So how can I force the class to load at runtime so NSClassFromString or objc_getclass will not return nil?