Getting Language and Locale Preferences Directly
There may be situations where you want to get the preferred locale ID or the list of languages directly from the user preferences. Mac OS X stores each user’s list of preferred languages in that user’s defaults database. The list of preferred languages is identified by the defaults key AppleLanguages
and is stored in the global variable NSGlobalDomain
. You can access that list using the NSUserDefaults
class in Cocoa or the Core Foundation preferences functions.
Important: If you get the user language preference from the defaults database, you must get the canonical form using theCFLocaleCreateCanonicalLanguageIdentifierFromString
function (in Mac OS X v10.4 and later) or CFLocaleCreateCanonicalLocaleIdentifierFromString
function (in Mac OS X v10.3 and later) before using the identifier.
The following example shows you to get the list of preferred languages from the defaults database using Cocoa. The returned array contains the languages associated with theAppleLanguages
key in the user's preferred order. Thus, in most cases, you would simply want to get the first object in the array.
NSUserDefaults* defs = [NSUserDefaults standardUserDefaults]; |
NSArray* languages = [defs objectForKey:@"AppleLanguages"]; |
NSString* preferredLang = [languages objectAtIndex:0]; |
The locale for the current user is also stored in the defaults database under theAppleLocale
key.
Important: Although you can get the user's preferred settings from the defaults database, it is recommended you use the CFBundle functions or NSBundle
class instead. The associated functions and methods of those objects return the preferred language or locale that is also supported by your application. (Bear in mind that the returned values may not correspond directly with the user's exact preferences.)