Question

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

Était-ce utile?

La solution

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 :)

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top