Why does NSClassFromString
return nil
? As per the definition it has to return class name.
How should I take care to rectify this problem? I need t
This happened to me when I add an external file to the Xcode project. Adding the .m file to Build Phases > Compile Sources solve the problem.
Why not decomposing all these calls ? This way, you can check the values between the calls:
Class myclass = NSClassFromString(@"Class_from_String");
id obj = [[myclass alloc] init];
[obj method_from_class];
By the way, is method_from_class
an instance method or a class method ? If it is the later, then you can directly call method_from_class
on the myclass
value:
[myclass method_from_class];
It is possible that your class is not getting linked if this is the only reference to it.
I had a factory method to instantiate various types of subclass. The factory had a switch statement that went to the appropriate subclass and alloc'd and init'ed it. I noticed that all of the alloc/init statements were exactly the same, except for the name of the class. So I was able to eliminate the entire switch block using the NSClassFromString() function.
I ran into the same problem - the return was nil. This was because the class was not used elsewhere in the program, so it wasn't getting linked, so it could not be found at runtime.
You can solve this by including the following statement:
[MyClass class];
That defeats the whole purpose of what I was trying to accomplish, but it might be all you need.
You also need to make sure the class you are trying to instantiate is included in the project. If you added it later, you made need to click the checkbox next to the Target you are building.
The Documentation for the function says:
Return Value The class object named by aClassName, or nil if no class by that name is currently loaded. If aClassName is nil, returns nil.
An example of how this should be properly used is as follows:
Class dictionaryClass = NSClassFromString(@"NSMutableDictionary");
id object = [[dictionaryClass alloc] init];
[object setObject:@"Foo" forKey:@"Bar"];
I also saw an oddity where adding the standard singleton code espoused by apple prevented the class from being loaded. The code was working as expected, then I added the singleton, and suddenly the NSClassFromString started returning nil. Commenting out the singleton code resulted in the NSClassFromString resolving the class correctly. I don't understand the interaction, but I think the singleton static var was somehow getting mangled to hide the class name...?