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

use*_*183 28 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];
}
Run Code Online (Sandbox Code Playgroud)

Jef*_*Jef 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];
}
Run Code Online (Sandbox Code Playgroud)

要按字母顺序排序,您可以添加

NSArray *sortedCountries = [countries sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
Run Code Online (Sandbox Code Playgroud)

请注意,排序数组是不可变的.

  • 在iOS8中,`country`是零. (2认同)

Arn*_*aud 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];  
}
Run Code Online (Sandbox Code Playgroud)


HAS*_*HAS 20

在Swift 3中,基础叠加层改变了很多.

let countryName = Locale.current.localizedString(forRegionCode: countryCode)
Run Code Online (Sandbox Code Playgroud)

如果您希望使用不同语言的国家/地区名称,则可以指定所需的区域设置:

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


Seb*_*ddd 6

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

NSString *countryName = [[NSLocale systemLocale] displayNameForKey:NSLocaleCountryCode value:countryCode];
Run Code Online (Sandbox Code Playgroud)

countryCode显然国家代码在哪里.(例如:"US")