ios - 使用 NSLocale 通过 Xcode 6.1 翻译语言代码

标签 ios objective-c xcode nslocale xcode6.1

自上次更新以来,我无法将语言代码(en、fr 等)翻译成各自的名称(英语、法语等)。

它可以在真实设备上运行,但不能在模拟器中运行。它可以使用以前版本的 Xcode 运行。我知道发行说明中写道 [NSLocale currentLocale] 在某些情况下可能会返回 en_US,但这并不能解释为什么它们不再“翻译” ”。我使用这段代码:

NSString* lang = @"en";
NSLog(@"%@",
    [[NSLocale currentLocale]
        displayNameForKey:NSLocaleIdentifier
        value:lang]
);

显示(null),而不是English

问题是我的应用程序因此在某些地方崩溃,所以我想知道是否有解决方法。

奇怪的是,Apple 给出的以下示例效果非常好。

NSLocale *frLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"];
NSString *displayNameString = [frLocale displayNameForKey:NSLocaleIdentifier value:@"fr_FR"];
NSLog(@"displayNameString fr_FR: %@", displayNameString);
displayNameString = [frLocale displayNameForKey:NSLocaleIdentifier value:@"en_US"];
NSLog(@"displayNameString en_US: %@", displayNameString);

最佳答案

来自Xcode release note

In some situations, [NSLocale currentLocale] may return en_US instead of the chosen locale in the iOS 8.1 simulator. (18512161)

+ (NSLocale *)autoupdatingCurrentLocale NS_AVAILABLE(10_5, 2_0); // generally you should use this method

+ (NSLocale *)currentLocale;    // an object representing the user's current locale

解决方法是使用第一个。在 currentLocal 实例上使用 objectForKey 是可行的。

NSString* lang = @"en_US";
NSLocale *currentLocal = [NSLocale autoupdatingCurrentLocale];
//get the localeIdentifier and create a new NSLocale.
id localIdentifier = [currentLocal objectForKey:NSLocaleIdentifier];
NSLocale *theLocal = [NSLocale localeWithLocaleIdentifier:localIdentifier];
NSLog(@"%@",[theLocal displayNameForKey:NSLocaleIdentifier
                                                  value:lang]
      );

关于ios - 使用 NSLocale 通过 Xcode 6.1 翻译语言代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26570195/

相关文章:

ios - UITableView 删除按钮没有出现

ios - AVPlayer 适用于模拟器,但不适用于设备

ios - Keychain 和 Secure Enclave 之间有什么区别

iOS 7 NavigationBar 不显示确切的 RGB 颜色

ios - 删除后如何重新安装ProjectUITests?

Xcode Objective C++——避免制作 .hh 文件?

ios - 所有行在每个部分标题下重复

ios - 在 iOS 上触发的旧本地通知

ios - 如何隐藏uiwebview导航按钮

ios - 'self' 未通过 Analyzer 设置为 '[(super or self) init…]' 的结果时使用的实例变量