NSLocaleCountryCode returns nil

China☆狼群 提交于 2019-12-23 07:28:58

问题


I have a bugreport that states a crash in the following line, where client is an instance of NSMutableDictionary

[client setObject:[[NSLocale currentLocale] objectForKey:NSLocaleCountryCode] forKey:@"country"];

My guess is, that NSLocaleCountryCode returns nil in this line, which leads to adding a nil object to an NSDictionary which would lead to a crash. The question is, has anybody experienced an issue like this before? Are there any reasons NSLocaleCountryCode could be nil for the currentLocale? The documentation doesn't say anything about returning a nil value and I thought this would always return a valid country.

Best regards, Michael


回答1:


There are others who have experienced this issue, when NSLocale is the "system locale". You need to be more defensive in your coding, by either not populating the key if it's nil or using [NSNull null]:

NSLocale *locale = [NSLocale currentLocale];
NSString *country = [locale objectForKey:NSLocaleCountryCode];
if (country != nil)
{
    [client setObject:country forKey:@"country"];
}



回答2:


My case was that for debug purposes I had selected custom language in run scheme in Xcode. I had EN, not system language.



来源:https://stackoverflow.com/questions/15202454/nslocalecountrycode-returns-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!