1

I want to do the following thing: if country == "Россия", some actions.. But my if-else statement doesn't work. What do I should do? Thanks in advance. My code:

   NSLocale *locale = [NSLocale currentLocale];
        NSString *countryCode = [locale objectForKey:NSLocaleCountryCode];
        NSString *country = [locale displayNameForKey:NSLocaleCountryCode value: countryCode];
        NSLog(@"%@", country);

        if (country == @"Россия") {
            NSLog(@"GO RUSSIA");
        }
        else {
            NSLog(@"You are not russian");
        }
Antonio MG
  • 20,382
  • 3
  • 43
  • 62
useboot
  • 67
  • 1
  • 5
  • When you compare with `==` you're checking to see if the two pointers address the exact same object. `isEqual` checks to see if the two objects, even if not the same object, have essentially equal contents. – Hot Licks Oct 22 '13 at 15:40
  • Sometimes I wonder whether I'm the only one reading the documentation when I have a doubt... – Gabriele Petronella Oct 22 '13 at 16:08

3 Answers3

8

You need to use comparison methods from NSString:

if ([country isEqualToString: @"Россия"]) {
   ...
}

Simply using == will compare raw pointer values, not actual string values.

Vladimir
  • 170,431
  • 36
  • 387
  • 313
  • Thank you. Everything is true and works. :) – useboot Oct 22 '13 at 15:38
  • This rule acts with only NSString? – useboot Oct 22 '13 at 15:38
  • Not just with NSString, for example `NSNumber` has it's own `isEqualToNumber` method for doing comparison checks. – Nicholas Smith Oct 22 '13 at 15:40
  • Normally you should compare any obj-c objects using special methods (isEqual: or isEqualToSmth: - custom classes can define custom comparison methods). Comparing pointers will almost never work – Vladimir Oct 22 '13 at 15:40
  • The only time you want to use `==` with objects is if you want to test if two variables point to the same instance. – Lance Oct 22 '13 at 15:49
  • 1
    `NSNumber` in particular can be confusing here, since some, but not all, `NSNumber`s are singletons. So you can have code where `num1 == num2` works fine when num1 and num2 are 12, but fails when they're 13. Always use the `isEqual` methods. – Rob Napier Oct 22 '13 at 16:02
  • Also you can use `==` to compare `NSString const *`, but again it's better to use `isEqualToString` to prevent stupid mistakes. – Gabriele Petronella Oct 22 '13 at 16:14
3

This:

if (country == @"Россия") 

Is not the way to compare a NSString.

Try this:

if ([country isEqualToString:@"Россия"])
Antonio MG
  • 20,382
  • 3
  • 43
  • 62
0

If you want to write the condition in == then only integer or Bool variable you can write And if you want to compare string contents then use equaltostring api below

if ([country isEqualToString: @"Россия"]) {
}
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56