I need to convert a list of country codes to a country array. Here is what I have done so far.
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. pickerViewArray = [[NSMutableArray alloc] init]; //pickerViewArray is of type NSArray; pickerViewArray =[NSLocale ISOCountryCodes]; }
The country codes can be represented either as a two-letter code (alpha-2) which is recommended as the general-purpose code, a three-letter code (alpha-3) which is more closely related to the country name and a three-digit numeric code (numeric-3) which can be useful if you need to avoid using Latin script.
ISO 3166-1 alpha-3 codes are three-letter country codes defined in ISO 3166-1, part of the ISO 3166 standard published by the International Organization for Standardization (ISO), to represent countries, dependent territories, and special areas of geographical interest.
You can get an identifier for a country code with localeIdentifierFromComponents:
and then get its displayName
.
So to create an array with country names you can do:
NSMutableArray *countries = [NSMutableArray arrayWithCapacity: [[NSLocale ISOCountryCodes] count]]; for (NSString *countryCode in [NSLocale ISOCountryCodes]) { NSString *identifier = [NSLocale localeIdentifierFromComponents: [NSDictionary dictionaryWithObject: countryCode forKey: NSLocaleCountryCode]]; NSString *country = [[NSLocale currentLocale] displayNameForKey: NSLocaleIdentifier value: identifier]; [countries addObject: country]; }
To sort it alphabetically you can add
NSArray *sortedCountries = [countries sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
Note that the sorted array is immutable.
This will work in iOS8 :
NSArray *countryCodes = [NSLocale ISOCountryCodes]; NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:[countryCodes count]]; for (NSString *countryCode in countryCodes) { NSString *country = [[NSLocale systemLocale] displayNameForKey:NSLocaleCountryCode value:countryCode]; [tmp addObject: country]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With