Search code examples
iosobjective-cxcode8ios10

Detect protocol availability in header file - Objective-C


I've downloaded the XCode 8.2 beta and in order to fix a warning on a project I had to add the following protocol to a header file: CAAnimationDelete which is available only from iOS 10.

The problem is that by only adding the protocol the project didn't compile on iOS versions prior to 10, so I've added the following check:

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_9_3
@interface CheckTest : UIView <CAAnimationDelegate>
#else
@interface CheckTest : UIView
#endif

Is this the correct approach?


Solution

  • I believe your use of the guard macros is correct, with one minor change; you want to check if you are compiling for iOS 10+, so test for that in the macros:

    #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
    @interface CheckTest : UIView <CAAnimationDelegate>
    #else
    @interface CheckTest : UIView
    #endif
    

    Don't forget to guard the CAAnimationDelegate method implementation using the same guard macros.

    If you are doing this in lots of classes, then it might be more convenient to do this in your pre-compiled header:

    #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10
    #define VIEWS_USE_CAANIMATIONDELEGATE 1
    #else
    #define VIEWS_USE_CAANIMATIONDELEGATE 0
    #endif
    

    and change the guard macros to:

    #if VIEWS_USE_CAANIMATIONDELEGATE
    @interface CheckTest : UIView <CAAnimationDelegate>
    #else
    @interface CheckTest : UIView
    #endif