Objective-C: How to check if a C function is supported

How to do a runtime check to see if I can use UIGraphicsBeginImageContextWithOptions , which is only available with iOS 4.

I know that I can check the [[UIDevice currentDevice] systemVersion] , but Apple recommends using things like NSClassFromString() or respondsToSelector: Is there respondsToSelector: for C functions?

+4
source share
3 answers

Here is another option I used.

C functions are pointers. If you are a “weak” link to the UIKit framework, on iOS 3 the function pointer will be just NULL , so you can check for the existence of the function by doing:

 if (UIGraphicsBeginImageContextWithOptions) { // On iOS 4+, use the main screen native scale factor (for iPhone 4). UIGraphicsBeginImageContextWithOptions(size, NO, 0.0); } else { UIGraphicsBeginImageContext(size); } 

See also: How to create weak Xcode 4 link structures?

+10
source

What you are probably interested in here is a weak connection . (See "Listing 3-2: Checking the availability of function C".)

+1
source

This is what I am going to:

 if ([mainScreen respondsToSelector:@selector(scale)]) { UIGraphicsBeginImageContextWithOptions(newSize, NO, [[UIScreen mainScreen] scale]); } else { UIGraphicsBeginImageContext(newSize); } 

I think this is good enough, but if you have any better suggestions, please respond.

-2
source

All Articles