有時候在項目中為了兼容低版本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版本。
