2017-09-24 31 views
10

我只想在当前设备的iOS版本低于特定版本时运行一段代码,如指定here。苹果给出的示例代码如下所示:否定Objective-C的@available关键字

if (@available(iOS 10.0, *)) { 
    // iOS 10.0 and above 
} else { 
    // below 10.0 
} 

但是,在某些场景下一个要运行的代码只有在当前的iOS版本低于特定版本。我认为下面的代码将工作:

if ([email protected](iOS 10.0, *)) { 
    // below 10.0 
} 

但是似乎这是不行的,而我在Xcode得到以下警告:

@available does not guard availability here; use if (@available) instead 

Here是LLVM提交该补充我看到的诊断。

有两种可能回退那个问题:

  1. 使用if-else变种无需添加任何代码到if块(不是很优雅)。
  2. 继续使用旧方法,例如-[NSProcessInfo isOperatingSystemAtLeastVersion:]

是否有另一种使用@available的方法,我错过了?

+1

我读过LLVM文章,它指出你不能在任何其他条件或指令中使用'@ available'。所以基本上我能想到的唯一方法是拥有一个空的'if'主体,但在'else'块内执行操作。这似乎是我唯一可能的方式。 – cramopy

+0

“但是,似乎这不起作用,我从Xcode得到以下警告:”只是因为有警告并不意味着它不起作用。警告称它不能保证可用性,但是您只是将它用作版本检查,而不是保证可用性。 – user102008

回答

0

您可以定义自己的自定义宏,您可以在整个应用程序中使用它们。例如: -

#define isIOS11() ([[UIDevice currentDevice].systemVersion doubleValue]>= 11.0 && [[UIDevice currentDevice].systemVersion doubleValue] < 12.0) 

#define SinceIOS9_2 ([[UIDevice currentDevice].systemVersion doubleValue]>= 4.2 && [[UIDevice currentDevice].systemVersion doubleValue] < 9.2) 

使用它象下面这样: -

if (isIOS11()) { 
    // Do something for iOS 11 
} else { 
    // Do something iOS Versions below 11.0 
} 

请让我知道这对你的作品。

+0

这是整洁。我想我会在某一天尝试那个。谢谢! – Akaino

+0

这不会抑制Xcode 9中的新“非保护可用性”警告。 – StatusReport

相关问题