Saturday, May 11, 2013

NSLocale ISOLanguageCodes example ios


ISOLanguageCodes

Returns an array of NSString objects that represents all known legal ISO language codes.
+ (NSArray *)ISOLanguageCodes
Return Value
An array of NSString objects that represents all known legal ISO language codes.
Discussion of [NSLocale ISOLanguageCodes]
Note that many of the language codes do not have any supporting locale data in OS X.
Example of [NSLocale ISOLanguageCodes]
NSLocale *englishLocale;
NSMutableDictionary *reverseLookupTable;
englishLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
reverseLookupTable = [NSMutableDictionary dictionaryWithCapacity:
    [[NSLocale ISOLanguageCodes] count]
];

for (NSString *languageCode in [NSLocale ISOLanguageCodes]) {
    NSString *displayName;
    displayName = [[englishLocale 
        displayNameForKey:NSLocaleLanguageCode
        value:languageCode
    ] lowercaseString];
    if (displayName) {
        [reverseLookupTable setObject:languageCode forKey:displayName];
    }
}

[englishLocale release];
Example of [NSLocale ISOLanguageCodes]
// Find a pretty display name for a few sample languages
NSArray *testLanguages;
testLanguages = [NSArray arrayWithObjects:
    @"en", @"fr", @"German", @"de", @"Italian", @"Some non-existing language", nil
];

for (NSString *language in testLanguages) {
    if ([[NSLocale ISOLanguageCodes] containsObject:[language lowercaseString]]) {
        // seems this already is a valid ISO code
        NSLog(
            @"%@ - %@", 
            language, 
            [[NSLocale currentLocale] displayNameForKey:NSLocaleLanguageCode value:language]
        );
    } else {
        // try finding an ISO code from our table
        NSString *isoCode;
        isoCode = [reverseLookupTable objectForKey:[language lowercaseString]];
        if (isoCode) {
            // yay
            NSLog(
                @"%@ - %@", 
                language, 
                [[NSLocale currentLocale] displayNameForKey:NSLocaleLanguageCode value:isoCode]
            );
        } else {
            // no result ... chances are this is not a real language, but hey
            NSLog(@"%@ - no result", language);
        }
    }
}