Unknown class

Even though Interface Builder is aware of a MyClass, I get an error when starting the application.

This happens when MyClass is part of a library, and does not happen if I compile the class directly in the application target.

 

Despite the "Unknown class MyClass in Interface Builder file." error printed at runtime, this issue has nothing to do with Interface Builder, but rather with the linker, which is not linking a class because no code uses it directly.

When the .nib data (compiled from the .xib) is loaded at runtime, MyClass is referenced using a string, but the linker doesn't analyze code functionality, just code existence, so it doesn't know that. Since no other source files references that class, the linker optimizes it out of existence when making the executable. So when Apple's code tries to load such a class, it can't find the code associated with it, and prints the warning.

By default, Objective-C targets will have -all_load -ObjC flags set by default, which will keep all of the symbols. But I had started with a C++ target, and didn't have that. Nevertheless, I found a way around this, which keeps the linker aggressive.

The hack I was originally using was to add an empty static routine like:

+(void)_keepAtLinkTime;

which does nothing, but that I would call once, such as:

int main(int argc,char** argv )
{
   
[MyClass _keepAtLinkTime];
   
// Your code.
}

This would force the linker to keep the whole class, and the error disappears.

As jlstrecker pointed out in the comments, we do not really need to add a _keepAtLinkTime method. Simply calling an existing one, such as:

   [MyClassclass];

does the trick (as long as you derive from an NSObject).

Of course, you can call this in any location of your code. I guess it could even be in unreachable code. The idea is to fool the linker into thinking that MyClass is used somewhere so that it isn't so aggressive in optimizing it out.

 

原文:

http://stackoverflow.com/questions/1725881/unknown-class-myclass-in-interface-builder-file-error-at-runtime

原文链接: https://www.cnblogs.com/ynwlgh/archive/2011/11/07/2238867.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    Unknown class

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/35959

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午12:45
下一篇 2023年2月8日 下午12:46

相关推荐