#iphone #objective-c #ios
#iPhone #objective-c #iOS
Вопрос:
Мне нужно преобразовать список кодов стран в массив country. Вот что я сделал до сих пор.
- (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];
}
Комментарии:
1. Извините, это типа NSMutableArray;
Ответ №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:)];
Обратите внимание, что отсортированный массив является неизменяемым.
Комментарии:
1. Спасибо, но список не отсортирован! как это сделать?
2. Я отредактировал свой ответ, предполагая, что вы хотите отсортировать его в алфавитном порядке.
3. В iOS8
country
равно нулю.4. Это возвращает название страны на языке. Я хотел бы получить название страны
Ответ №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 наложение основы немного изменилось.
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
, очевидно, код страны. (например: «США»)