Objective-C @available guard AND'ed with more conditions

前端 未结 8 1313
眼角桃花
眼角桃花 2021-01-01 11:17

Objective-C has an @available expression in XCode 9+ / LLVM 5+ that allows you to guard a block of code to at least a certain OS version so that it won\'t emit unguarded ava

8条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-01 11:45

    #define SUPPRESS_AVAILABILITY_BEGIN \
        _Pragma("clang diagnostic push") \
        _Pragma("clang diagnostic ignored \"-Wunsupported-availability-guard\"")\
        _Pragma("clang diagnostic ignored \"-Wunguarded-availability-new\"")
    
    #define SUPPRESS_AVAILABILITY_END \
        _Pragma("clang diagnostic pop")
    
    #define AVAILABLE_GUARD(platform, os, future, conditions, codeIfAvailable, codeIfUnavailable) \
        SUPPRESS_AVAILABILITY_BEGIN \
        if (__builtin_available(platform os, future) && conditions) {\
            SUPPRESS_AVAILABILITY_END \
            if (@available(platform os, future)) { \
                codeIfAvailable \
            } \
        } \
        else { \
            SUPPRESS_AVAILABILITY_END \
            codeIfUnavailable \
        }
    

    Usage:

    AVAILABLE_GUARD(iOS, 11.0, *, true, {
        printf("IS AVAILABLE");
    },
    {
        printf("NOT AVAILABLE");
    });
    

    It works by using @available as a condition with additional optional conditions. Since you lose the ability to "guard", I suppressed the unguarded warnings but I also added an extra guard there to guard the rest of the code.. This makes it so you essentially lost nothing..

    You get the guarding, you get the warnings gone and you get the extra conditions..

提交回复
热议问题