iOS Framework weak link: undefined symbols error

假装没事ソ 提交于 2019-12-03 04:28:03

From the description of your issue, I assume you already know how to make Xcode weakly link against the framework by setting it as 'Optional'.

You have two problems to solve: Class availability and symbol availability. Apple covers this in the Framework Programming Guide: Frameworks and Weak Linking and the SDK Compatibility Guide: Using SDK Based Development

Class availability

This is pretty straightforward: use NSClassFromString() to see if the class is available in the current environment.

if (NSClassFromString("CLLocationManager") != NULL){

If the class is available it can be instantiated and sent messages, otherwise it cannot.

Symbol availability

What you are specifically interested in is using constants or structs from a weakly linked framework. A C-style function would be similar, but those are not a concern when using CoreLocation. We'll use a CoreLocation constant as an example.

Every time you use it you MUST check to make sure it exists:

if (&kCLErrorDomain != NULL){
   // Use the constant
}

Note that the & takes the address of the constant for the comparison. Also note that you CANNOT do this:

if (kCLErrorDomain){
   // Use the constant
}

Or this:

if (&kCLErrorDomain){
   // Use the constant
}

Constant symbols can also be lookup up at runtime using dlsym. Using the negation operator in this way will not work. You must check the address of the constant against the NULL address.

I have put a very simple example of an application that is using a static library which weak links against Core Location on GitHub. The example application does not link against Core Location:

But the dependency does, as an optional (weak) framework:

You could wrap any code and imports that uses the CoreLocation framework in a

#ifdef __CORELOCATION__
... do stuff
#endif

This will negate all CoreLocation code when the framework is not being linked at compile time

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