NSClassFromString returns nil

后端 未结 7 1417
礼貌的吻别
礼貌的吻别 2020-12-09 04:28

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

7条回答
  •  醉梦人生
    2020-12-09 04:55

    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.

提交回复
热议问题