OGeek|极客世界-中国程序员成长平台

标题: ios - 使用 NSLocale 使用 Xcode 6.1 翻译语言代码 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 12:11
标题: ios - 使用 NSLocale 使用 Xcode 6.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);



Best Answer-推荐答案


来自 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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4