简体   繁体   English

如何在cocoa中获取系统区域设置和系统语言

[英]How to get system locale and system language in cocoa

I want to get the system default language and system locale. 我想获得系统默认语言和系统区域设置。

I have tried the following code snippet to get the system current locale as the following 我已经尝试了以下代码片段来获取系统当前语言环境,如下所示

NSLocale *locale;
locale = [NSLocale systemLocale];

NSString * localLanguage = [locale objectForKey:NSLocaleIdentifier];
NSLog (@"Language : %@", localLanguage); 

NSLog(@"System locale Identifier %@",[locale localeIdentifier]);

But nothing is displayed with System locale Identifier.If it is currentlocale it is giving the correct result.Why system locale is not giving any value and how to get system default language not the user preferred language?please help 但系统区域设置标识符没有显示任何内容。如果它是currentlocale,它会给出正确的结果。为什么系统区域设置没有给出任何值以及如何获取系统默认语言而不是用户首选语言?请帮助

你可以简单地使用: NSString* language = [[NSLocale preferredLanguages] objectAtIndex:0];

The default NSLocaleIdentifier is intentionally @"" to indicate that there is no current selection. 默认的NSLocaleIdentifier有意为@""表示没有当前选择。 According to Apple, systemLocale is just a fallback for keys that aren't implemented in the user's selected locale ( currentLocale ), and since that's always set and it's always under the user's control, it makes sense. 根据Apple的说法, systemLocale只是未在用户选择的语言环境( currentLocale )中实现的键的后备,并且因为它始终设置并且始终在用户的控制之下,所以它是有意义的。

If you want to follow the user's list of preferred languages, you want to use + preferredLanguages , which returns a list of the languages that the user prefers, in the order in which they prefer them. 如果要按照用户的首选语言列表,您希望使用+ preferredLanguages ,它按照用户喜欢的顺序返回用户喜欢的语言列表。 This works for both OSX and iOS, and serves to provide an appropriate fallback for the system when choosing languages. 这适用于OSX和iOS,并且在选择语言时用于为系统提供适当的后备。

For testing, you can use the command-line switch -AppleLanguages with a value of a comma-separated, parenthesis-surrounded array (example: (DE,FR,EN) ) and Xcode will simulate that being the preferred languages list for the user. 对于测试,您可以使用命令行开关-AppleLanguages ,其值为逗号分隔,括号括起的数组(例如: (DE,FR,EN) ),Xcode将模拟这是用户的首选语言列表。

Since the user sets the preferred languages (at least in OSX), the operating system will follow the list when it chooses localized data for the user. 由于用户设置首选语言(至少在OSX中),操作系统将在为用户选择本地化数据时遵循列表。 Generally, doing anything more than using the macros is considered unnecessary due to this fact. 通常,由于这一事实,除了使用宏之外的任何操作都被认为是不必要的。 However, you can manually look at the value if you have non-resource information you need to localize. 但是,如果您有本地化所需的非资源信息,则可以手动查看该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM