NSClassFromString returns nil

浪子不回头ぞ 提交于 2019-11-28 08:20:12

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

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.

Al Smith

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.

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.

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.

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

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...?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!