Weak linking on iPhone refuses to work

删除回忆录丶 提交于 2019-11-26 17:44:20

问题


I've got an iPhone app that's mainly targetting 3.0, but which takes advantage of newer APIs when they're available. Code goes something like this:

if (UIApplicationDidEnterBackgroundNotification != NULL) {
    [nc
        addObserver: self
        selector:    @selector(irrelevantCallbackName:)
        name:        UIApplicationDidEnterBackgroundNotification
        object:      nil];
}

Now, according to everything Apple's ever said, if the relevant APIs are weakly linked, that will work fine because the dynamic linker will evaluate UIApplicationDidEnterBackgroundNotification to NULL. Except that it doesn't. The application compiles, but as soon as it hits if (UIApplicationDidEnterBackgroundNotification != NULL) it crashes with EXC_BAD_ACCESS.

Is this simply a matter of a compiler flag I need to set? Or am I going about this the wrong way?


回答1:


Aaand I figured it out. For symbols that are not functions (extern const int foobar, for instance), you have to compare against the address of the symbol, not the symbol itself, so:

if (&UIApplicationWillEnterForegroundNotification != NULL)
    etc;

Which in retrospect is kind of obvious, but I still fault the entire universe around me for not ever mentioning the distinction.




回答2:


Here is what I had to do when checking for an external framework constant.

const CLLocationAccuracy * ptr = &kCLLocationAccuracyBestForNavigation;
BOOL frameworkSupports = (ptr != NULL);
if (frameworkSupports) {
    return kCLLocationAccuracyBestForNavigation;
} else {
    return kCLLocationAccuracyBest;
}

It would not work without the ptr variable.



来源:https://stackoverflow.com/questions/3002833/weak-linking-on-iphone-refuses-to-work

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