NSClassFromString returns nil

Viewed 29449

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 to instantiate a class from string and call the method, which is in the class, using the instance created.

This is how my code looks like:

id myclass = [[NSClassFromString(@"Class_from_String") alloc] init];
[myclass method_from_class];

But the method_from_class function is not being called, control is not going into it. And my code is error free. Any idea how to solve this in Objective-C?

7 Answers

If you are trying to instantiate a class from a static library, you must add the "-ObjC" flag to the "Other Linker Flags" build setting.

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"];

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];
Related