xcode针对不同IOS版本的代码编译问题

有时候在项目中为了兼容低版本IOS系统,通常会针对不同的OS版本写不同的代码,例如:

#define IS_IOS7_OR_LATER            ([[UIDevice currentDevice].systemVersion floatValue] >=7.0)

if(IS_IOS7_OR_LATER)
{
    [[UINavigationBar appearance] setBarTintColor:[UIColor standardLightGray]]; //IOS7时才有的API
}
else
{
    [[UINavigationBar appearance] setTintColor:[UIColor standardLightGray]];
}

这段代码在xcode5/xcode6上编译是没有问题的,但是在xcode4.6上编译通过不了,因为这个if/else要在运行时才能知道判断条件是否成立,在代码编译时是不知道的。可以这样处理:

#define IS_IOS7_OR_LATER            ([[UIDevice currentDevice].systemVersion floatValue] >=7.0)

#ifdef __IPHONE_7_0
    if(IS_IOS7_OR_LATER)
    {
        [[UINavigationBar appearance] setBarTintColor:[UIColor standardLightGray]];
    }
    else
    {
        [[UINavigationBar appearance] setTintColor:[UIColor standardLightGray]];
    }
#else
    [[UINavigationBar appearance] setTintColor:[UIColor standardLightGray]];
#endif
__IPHONE_7_0是系统的宏,在编译时可以确定它有没有定义。这样的话代码在xcode4.6/xcode5/xcode6上均可编译成功。
但是如果在xcode4.6(IOS6)上编译,编译时xcode会把#ifdef~#else之间的代码删除掉,只会编译#else~#endif之间的代码,最终你项目中针对高版本IOS的代码不会被执行,即使你是在IOS8的手机上运行该程序。
所以如果你想同时兼容高版本和低版本的IOS,就要使用高版本的xcode来编译代码,同时如果你希望项目在低版本的xcode上编译运行,请在代码中使用上面的宏来区分IOS版本。
原文地址:https://www.cnblogs.com/java-koma/p/4056513.html