开发者

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

开发者 https://www.devze.com 2023-03-19 09:26 出处:网络
How can I perform a run-time 开发者_开发问答check to see if I can use UIGraphicsBeginImageContextWithOptions, which is only available starting with iOS 4.

How can I perform a run-time 开发者_开发问答check to see if I can use UIGraphicsBeginImageContextWithOptions, which is only available starting with iOS 4.

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


Here's another option, which I've been using.

C functions are pointers. If you "weak" link to UIKit framework, on iOS 3 the function pointer will simply be NULL, so you can test for the existence of the function by doing:

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

See also: How do I weak link frameworks on Xcode 4?


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


This is what I'm going with:

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 answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消