문제

I am stumped as to why this code isn't working as per the comment below:

NSString *countryCode = [[NSLocale currentLocale] objectForKey: NSLocaleCountryCode];
NSLog(@"Country Code: %@", countryCode);

if (countryCode == @"US") {
    NSLog(@"Country is USA"); // Does not execute since the if does not pass
}

The locale is en_US therefore the country code is US. Everything is correct on that part of things. What am I doing wrong, and how do I get "Country is USA" to display?

Thank you!

Testing on iOS 5.1 and 6.0, same result

도움이 되었습니까?

해결책

Strings cannot be compared using the == operator, try using isEqualToString: instead:

NSString *countryCode = [[NSLocale currentLocale] objectForKey: NSLocaleCountryCode];
NSLog(@"Country Code: %@", countryCode);

if ([countryCode isEqualToString: @"NL"]) {
    NSLog(@"Country is NL");
}

Used NL since I'm in the Netherlands :)

다른 팁

You must use the isEqualToString: method to compare the contents two strings. The == operator tests for equality of the two pointers and therefore returns 0.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top