Подтвердить что ты не робот

Преобразование кодов стран в названия стран

Мне нужно преобразовать список кодов стран в массив стран. Вот что я сделал до сих пор.

- (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];
}
4b9b3361

Ответ 1

Вы можете получить идентификатор кода страны с localeIdentifierFromComponents:, а затем получить его displayName.

Итак, чтобы создать массив с названиями стран, вы можете:

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];
}

Для сортировки в алфавитном порядке вы можете добавить

NSArray *sortedCountries = [countries sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

Обратите внимание, что отсортированный массив является неизменным.

Ответ 2

Это будет работать в 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];  
}

Ответ 3

В Swift 3 наложение Foundation немного изменилось.

let countryName = Locale.current.localizedString(forRegionCode: countryCode)

Если вам нужны названия стран на разных языках, вы можете указать желаемый язык:

let locale = Locale(identifier: "es_ES") // Country names in Spanish
let countryName = locale.localizedString(forRegionCode: countryCode)

Ответ 4

В iOS 9 и выше вы можете получить имя страны из кода страны, выполнив:

NSString *countryName = [[NSLocale systemLocale] displayNameForKey:NSLocaleCountryCode value:countryCode];

Где countryCode, очевидно, код страны. (например, "США" )