【问题标题】:xcode 6.1 iOS 8.1 NSLocale displayNameForKey NSLocaleIdentifier return nilxcode 6.1 iOS 8.1 NSLocale displayNameForKey NSLocaleIdentifier 返回 nil
【发布时间】:2014-12-24 03:12:44
【问题描述】:
- (NSString *)countryNameByCode:(NSString*)countryCode { NSString *identifier = [NSLocale localeIdentifierFromComponents:@{NSLocaleCountryCode: countryCode}]; NSString *countryName = [[NSLocale currentLocale] displayNameForKey:NSLocaleIdentifier value:identifier]; 返回国家名称; }

这返回了nil。为什么?

【问题讨论】:

  • 这个问题只有模拟器。我今天在设备上进行了测试,我得到了正确的国家名称。
  • 我自己在模拟器上遇到了这个问题——我用所有国家的列表填充了一个表格视图,在模拟器中它只是因为 displayNameForKey 返回 null 而崩溃。我已经在所有带有 8.1 的模拟器设备上尝试过,它们都崩溃了。带有 iOS 7.1 的 iPhone4 和 iPhone 5 模拟器运行良好。我的代码在安装了 8.1 的物理设备 iPhone4s 和 iPhone5 上也运行良好,所以我猜它只是一个 Xcode 错误。解决方案 - 在苹果修复之前,在设备上进行测试 - 这是一个错误,因为我手头没有 6 和 6 plus :(

标签: ios objective-c nslocale


【解决方案1】:

这是一个已知的 Apple 问题,仅适用于 iOS 8.1 模拟器 - 无法在 8.1 设备上重现。请参阅以下 Xcode 6.1 发行说明中的​​问题描述:

本地化和键盘设置(包括第 3 方键盘)是 iOS 中的 Safari、地图和开发者应用程序未正确识别 8.1 模拟器。 [NSLocale currentLocale] 返回 en_US 并且只有英文和表情符号键盘可用。 (18418630, 18512161)。

更多详情请见Xcode 6.1 Release Notes

【讨论】:

    【解决方案2】:

    请尝试以下代码,它应该可以工作。我在我的设备和模拟器 8.1 上都试过了

    - (NSString *)countryNameByCode:(NSString*)countryCode {
      return [[NSLocale systemLocale] displayNameForKey:NSLocaleCountryCode value:countryCode];
    }
    

    【讨论】:

      【解决方案3】:

      这对我有用

      NSLocale *currentLocale = [[NSLocale alloc] initWithLocaleIdentifier:[NSLocale currentLocale].localeIdentifier];
      
       for (AVSpeechSynthesisVoice *voice in [AVSpeechSynthesisVoice speechVoices]) {
                  NSString *languageLocalised = [currentLocale displayNameForKey:NSLocaleIdentifier value:voice.language];
                  NSLog(@"%@ displayNameForKey %@: %@", currentLocale.localeIdentifier, voice.language, languageLocalised);
       }
      

      【讨论】:

      • 旁注:您的第一行包含冗余代码。您可以将其缩短为 NSLocale *currentLocale = [NSLocale currentLocale];
      【解决方案4】:
      - (NSString *)countryNameByCode:(NSString*)countryCode 
      {
          NSString *identifier = [[NSLocale preferredLanguages] firstObject];
          NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:identifier];
          NSString *countryName = [locale displayNameForKey:NSLocaleIdentifier value:countryCode];
          return countryName;
      }
      

      我不明白为什么[[NSLocale currentLocale] displayNameForKey...] 不返回iOS 8 中的国家/地区名称,但上面的代码应该可以解决您的问题。

      【讨论】:

      • 显然返回的是语言名称(法语、德语...),而不是国家/地区。
      • 是的,在我这边也没有工作...对于国家代码“US”,我得到一个标识符“_US”,它导致国家名称为零。
      • 解决方案有效,您只需要使用NSLocaleCountryCode 而不是NSLocaleIdentifier
      【解决方案5】:
      NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-23
        • 2015-01-26
        • 2015-01-11
        • 2014-12-21
        • 1970-01-01
        • 2015-01-08
        • 2013-04-23
        • 2014-12-18
        相关资源
        最近更新 更多