-1

Possible Duplicate:
Comparing Strings in Cocoa
Why is this code not recognising the NSString as being equal?

I have a value set to @"YES" in the NSUserDefaults. When I run this method...

- (void) checkForHint {
    NSLog(@"call:checkForHint");
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSLog(@"valueForKeyInDefaults:%@",[defaults valueForKey:@"giveHint"]);
    if ([defaults valueForKey:@"giveHint"] == @"YES") {
        NSLog(@"need to give hint");
        // replace a letter at random
        int i=0;
        bool found = NO;
        while (!found && i<NUM_CHARACTERS_IN_LEVEL_STRING) {
            NSLog(@"searching at index %i",i);
            if ([buttons objectAtIndex:i] && 32==[[levelSavedSolutionArray objectAtIndex:i] intValue]) {
                found = YES;
            }
            i++;
        }
        i--;
        // We need to select all the buttons at this unsolved space
        [self buttonClicked:[buttons objectAtIndex:i]];
        // update the entries in all selected buttons
        [self keyAct:[[levelStringArray objectAtIndex:i] intValue]];
    }
}

the output to the console is:

2012-03-28 23:11:41.799 (APPID) call:checkForHint
2012-03-28 23:11:41.800 (APPID) valueForKeyInDefaults:YES

I dont understand why this if statement isnt returning true.. Anyone who could help that would be greatly appreciated. I have a feeling its because the two strings are different instances that happen to have the same values but I dont know how to fix this.

Community
  • 1
  • 1
bkbeachlabs
  • 2,121
  • 1
  • 22
  • 33
  • 4
    A counter question: **Why is `==` being used for *string* comparison?** Search for duplicates, you will find them... in any case, Objective-C *does not* have operator overloading which is why `==` that will never work reliably for *value equality* of two NSObjects. –  Mar 29 '12 at 03:18
  • sorry i dont really know what to search for. is there a specific method for comparing strings? thanks – bkbeachlabs Mar 29 '12 at 03:20
  • Search for "compare nsstrring" or "equals nsstring". –  Mar 29 '12 at 03:20

1 Answers1

6

Operation == is comparing pointers in this case. Obviously you are comparing two different objects: @"YES" which is a literal string and the object returned by [defaults valueForKey:@"giveHint"] method call.

If you need to compare strings by their content use [[defaults valueForKey:@"giveHint"] isEqualToString:@"YES"]

Davyd Geyl
  • 4,578
  • 1
  • 28
  • 35