【问题标题】:Converting Country Codes to Country Names将国家代码转换为国家名称
【发布时间】:2018-03-20 17:41:39
【问题描述】:

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

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

【问题讨论】:

  • 对不起,它是 NSMutableArray 类型的;

标签: iphone objective-c ios


【解决方案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:)];

注意排序后的数组是不可变的。

【讨论】:

  • 谢谢,但列表未排序!该怎么做?
  • 我编辑了我的答案,假设您想按字母顺序对其进行排序。
  • 在 iOS8 中 country 为零。
  • 那是返回国家语言名称。我想得到国家名称
【解决方案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 显然是国家代码。 (例如:“美国”)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-10
        • 1970-01-01
        • 1970-01-01
        • 2016-06-11
        • 2012-09-12
        相关资源
        最近更新 更多