根据iOS版本编译

时间:2014-01-08 11:09:22

标签: ios ios7 compiler-errors

如果根据不同的iOS版本有不同的方法。实现这一目标的最佳做法是什么。 例如iOS 6有[aString sizeWithFont:[UIFont boldSystemFontOfSize:11.0f]];来获取aString的宽度。在iOS 7中,方法[aString sizeWithAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:11.0f]}]实现了相同的功能。  我的应用程序将在iOS 6和iOS 7上运行。我使用以下代码

@try {
        textSize = [labelText sizeWithAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:11.0f]}];

        }
@catch (NSException *exception) {
        textSize = [labelText sizeWithFont:[UIFont boldSystemFontOfSize:11.0f]];
        }

xCode总是抱怨弃用的方法。但是这样做的最佳做法是什么?

6 个答案:

答案 0 :(得分:2)

选中respondsToSelector:

if ([labelText respondsToSelector:@selector(sizeWithAttributes:)]) {
    textSize = [labelText sizeWithAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:11.0f]}];
}

if ([labelText respondsToSelector:@selector(sizeWithFont:)]) {
    textSize = [labelText sizeWithFont:[UIFont boldSystemFontOfSize:11.0f]];
}

答案 1 :(得分:0)

尝试使用

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_0
  // iOS 7 code here
#else
  // iOS 6 code here
#endif

不要忘记#import Availability.h

注意:#if或#ifdef仅在编译时有效。他们无法在运行时做出决定。

答案 2 :(得分:0)

您可以使用以下iOS检查:

if ([[[UIDevice currentDevice ] systemVersion]intValue] < 7.0)
    {
        // Is below iOS 7
    }
    else
    {
       // Above iOS 7
    }

答案 3 :(得分:0)

使用此宏。

#define IS_IOS7 ((floor(NSFoundationVersionNumber)>NSFoundationVersionNumber_iOS_6_1))

在任何课程中使用此宏,并在代码中的任意位置检查iOS版本

if(IS_IOS7)
      textSize = [labelText sizeWithAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:11.0f]}];
else
      textSize = [labelText sizeWithFont:[UIFont boldSystemFontOfSize:11.0f]];

或者您可以使用respondsToSelector来检查方法

if ([labelText respondsToSelector:@selector(sizeWithAttributes:)]) {
    textSize = [labelText sizeWithAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:11.0f]}];
}
else if ([labelText respondsToSelector:@selector(sizeWithFont:)]) {
    textSize = [labelText sizeWithFont:[UIFont boldSystemFontOfSize:11.0f]];
}

答案 4 :(得分:-1)

最好的方法是检查选择器是否会得到响应,就像我用来获取UDID或广告标识符一样

- (NSString *) advertisingIdentifier {
    if (!NSClassFromString(@"ASIdentifierManager")) {
        SEL selector = NSSelectorFromString(@"uniqueIdentifier");
        if ([[UIDevice currentDevice] respondsToSelector:selector]) {
            return [[UIDevice currentDevice] performSelector:selector];
        }
    }
    return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
}

答案 5 :(得分:-1)

检查操作系统版本,而不是相应地进行操作

NSString *ver = [[UIDevice currentDevice] systemVersion];
float ver_float = [ver floatValue];
if (ver_float >= 7.0) {
    // iOS 7 or later
    textSize = [labelText sizeWithAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:11.0f]}];
}
else {
    // iOS 6 or previous
    textSize = [labelText sizeWithFont:[UIFont boldSystemFontOfSize:11.0f]];
}