0

Possible Duplicate:
Why is my comparing if statement not working?

I am attempting to check to see if a particular setting was set to "On" or "Off". Here is my code:

BOOL switchOn;
if ([self loadSettings:@"useLocation"] == @"On"){
    switchOn = YES;
    NSLog(@"Use Location (Yes): %@",[self loadSettings:@"useLocation"]);
}else{
    switchOn = NO;
    NSLog(@"Use Location (No): %@",[self loadSettings:@"useLocation"]);
}
NSLog(@"Switch On: %@",switchOn ? @"YES":@"NO");

Printed to the log is:

Use Location (No): On

Switch On: NO

You can see that for the "Use Location (No)" to come up, the function should not have returned "On". But it did return "On". Am I not comparing them correctly?

Here is my code for loading the defaults:

- (NSString *)loadSettings: (NSString *)key{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults synchronize]; // this method is optional
    
    // Get the results out
    NSString *results = [defaults stringForKey:key];
    
    return results;
}

I'm returning an NSString, so I'm really not sure what the issue is. I get no errors at all in the build environment before or after compiling.

Community
  • 1
  • 1
James
  • 3,765
  • 4
  • 48
  • 79

3 Answers3

5

== compares pointers, so even if two NSStrings have the same content they may not have the same address in memory, in which case == would be false.

Use `isEqualToString' instead:

if ([[self loadSettings:@"useLocation"] isEqualToString:@"On"]){
...
yuji
  • 16,695
  • 4
  • 63
  • 64
  • Thanks for the reply. You got beat by just a little, but this is the answer, so still get a + vote. – James Mar 27 '12 at 19:26
4

You have to use isEqualToString:

Ex:

if ([myString isEqualToString:@"YES"]) {
    //do stuff
}

The way you're doing it is actually comparing the pointers to the objects themselves.

rosslebeau
  • 1,283
  • 6
  • 6
  • Worked great. So weird. Do I have to do that for any string, or only from strings returned from functions? I'll mark this as the answer once it lets me. – James Mar 27 '12 at 19:25
  • Any string. Even constants: `[@"TestString" isEqualToString:@"TestString"]` returns `YES` – rosslebeau Mar 27 '12 at 19:31
3

Use:

if([[self loadSettings:@"useLocation"] isEqualToString: @"On"] {
    switchOn = YES;
}

As documented here

lnafziger
  • 25,760
  • 8
  • 60
  • 101
dasdom
  • 13,975
  • 2
  • 47
  • 58
  • Thanks for the reply. You got beat by just a little, but this is the answer, so still get a + vote. – James Mar 27 '12 at 19:26