自上次更新以来,我无法将语言代码(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);
最佳答案
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/