将国家代码转换为国家/地区名称

时间:2011-11-11 17:41:45

标签: iphone objective-c ios

我需要将国家/地区代码列表转换为国家/地区数组。这是我到目前为止所做的。

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

4 个答案:

答案 0 :(得分:56)

您可以使用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 :(得分:25)

这适用于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];  
}

答案 2 :(得分:20)

在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)

答案 3 :(得分:6)

在iOS 9及更高版本中,您可以通过执行以下操作从国家/地区代码中检索国家/地区名称:

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

countryCode显然是国家/地区代码。 (例如:“US”)

相关问题