String compare not working

Discussion in 'iOS Programming' started by jchildress, Sep 7, 2008.

  1. jchildress macrumors member

    Jul 9, 2008
    for some reason, I can't get a string compare to return true, even though the two strings are identical.

    First I tried:
    if (string1 == string2) {
        NSLog(@"Strings Match");
    This did not work.

    Then I tried:
    if ([string1 compare: string2] == YES) {
        NSLog(@"Strings Match");
    This did not work either. I also tried upper and lower casing the strings before the compare, but that did nothing. I also tried caseInsensitiveCompare:

    I logged the two strings to the console before the compare, and they appear identical to each other. I'm beginning to think that maybe there is some difference in the format of the two strings. I'm declaring both of them as NSStrings.

    Does anybody have any suggestions?
  2. admanimal macrumors 68040

    Apr 22, 2005
    NSString's compare method doesn't return a BOOL, it returns an NSComparisonResult (basically an int). Have the app check which of the 3 possible results it gets, it might help you solve the problem.
  3. Luke Redpath macrumors 6502a

    Nov 9, 2007
    Colchester, UK
    Alternatively, use:

    if([string1 isEqual:string2]) {
     // do something
  4. robbieduncan Moderator emeritus


    Jul 24, 2002
    Or if you know for sure that both are NSString objects

    if ([string1 isEqualToString:string2]
    // Do it
    I have been told in the fast this is slightly more efficient that calling isEqual...
  5. Ron C macrumors member

    Jul 18, 2008
    I too am a Obj-C newbie, but the compare method sounds a lot like C's strcmp(str1,str2), which returns one of three values -
    • a value less than 0 if str1 is "less than" str2
    • 0 if str1 equals str2
    • a value greater than 0 if str1 is "greater than" str2
    Looking at the NSString documentation for 2 seconds shows that this is indeed the case. The corresponding values are:
    • NSOrderedAscending - The left operand is smaller than the right operand.
    • NSOrderedSame - The two operands are equal.
    • NSOrderedDescending - The left operand is greater than the right operand.

    (this lurking obj-c newbie learns a lot from these kinds of posts, so thanks to admanimal for showing patience :D)

    Ron C.
  6. kainjow Moderator emeritus


    Jun 15, 2000
    A tip if in Xcode: command-click a method/class/variable, etc and you'll be taken to its definition (or implementation). Especially helpful for quickly glancing at a method to see what arguments it takes and what it returns.
  7. jchildress thread starter macrumors member

    Jul 9, 2008
    Thanks RobbieDuncan, the "isEqualToString:" method worked great.

Share This Page