2011-11-11 134 views
26

我需要將國家代碼列表轉換爲國家/地區陣列。這是我迄今爲止所做的。將國家代碼轉換爲國家名稱

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

對不起,這是類型的NSMutableArray的; – user1036183

+2

接受一些答案(關於您之前的問題),以便您回饋社區。 – Jef

回答

55

你可以得到一個國家代碼的標識符與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:)]; 

注意數組排序是不可改變的。

+0

謝謝,但列表沒有排序!怎麼做 ? – user1036183

+0

我編輯了我的答案,假設您想按字母順序排序。 – Jef

+0

它像一個魅力。做得好! :D –

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

在iOS系統9或以上,你可以通過執行檢索來自國家代碼的國家名稱:

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

哪裏countryCode顯然是國家代碼。 (例如:「美國」)

17

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

非常感謝你:) – fancy

相關問題