#ifdef条件不起作用

时间:2012-05-25 08:28:46

标签: iphone objective-c ios

我正在使用如下的条件代码,

我想仅在ios5.0和>中运行某些代码ios5.0(我的意思是我也想支持ios5.0和5.1版本)

但以下情况似乎不起作用。 (目前我的开发版本是5.1,但下面的代码片段未被识别。控件不会进入它。)

请让我知道你的想法

#ifdef __IPHONE_5_0_OR_LATER

3 个答案:

答案 0 :(得分:4)

#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_5_0
// iPhone 5.0 code here
#endif


#define __IPHONE_2_0     20000
#define __IPHONE_2_1     20100
#define __IPHONE_2_2     20200
#define __IPHONE_3_0     30000
#define __IPHONE_3_1     30100
#define __IPHONE_3_2     30200
#define __IPHONE_4_0     40000
#define __IPHONE_4_1     40100
#define __IPHONE_4_2     40200
#define __IPHONE_4_3     40300
#define __IPHONE_5_0     50000
#define __IPHONE_5_1     50100
#define __IPHONE_NA      99999  /* not available */

How to target a specific iPhone version?

答案 1 :(得分:2)

#ifdef是一个编译指令,因此它将在编译时而不是运行时进行评估。

因此,如果您将此代码添加到代码中,那么如果您的目标SDK与#ifdef匹配,那么调用if的方法会调用所有方法。因此,如果您为iOS 4和5编译应用程序并将所有仅5个方法放在#ifdef io5中,则应用程序将在iOS 4上崩溃,因为将调用这些方法。

如果你想检查某种方法是否可用,那么你应该这样做:

以下是从其父级中解除模态视图控制器的示例。由于iOS 5中parentViewController已更改为presentingViewController,因此我们会检查presentingViewController是否可用并使用它。

if ([self respondsToSelector:@selector(presentingViewController)]) {
    [self.presentingViewController dismissModalViewControllerAnimated:YES];
} else {
    [self.parentViewController dismissModalViewControllerAnimated:YES];
}

同样用于检查班级是否可用:

if ([MPNowPlayingInfoCenter class]) {
     MPNowPlayingInfoCenter *center = [MPNowPlayingInfoCenter defaultCenter];
     NSDictionary *songInfo = /* ... snip ... */;
    center.nowPlayingInfo = songInfo;
}

答案 2 :(得分:0)

NSArray *versionCompatibility = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];

if ( 5 == [[versionCompatibility objectAtIndex:0] intValue] ) { /// iOS5 is installed

    // Put iOS-5 code here

} else { /// iOS4 is installed

    // Put iOS-4 code here         

}
相关问题