question about objective-c: comparing strings to substrings.

Discussion in 'Mac Programming' started by ausername, Feb 28, 2009.

  1. macrumors newbie

    Joined:
    Feb 28, 2009
    #1
    I've run into a snag... Could someone please tell me why this doesn't work? and show me how I can make it work? thanks :)


    #import <Foundation/Foundation.h>
    int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSString *str1 = @"abc";
    NSString *str2;
    str2 = [str1 substringWithRange:NSMakeRange(0,1)];
    if (str2 == @"a")
    printf("YES");
    else
    printf("NO");

    [pool drain];
    return 0;
    }



    It gives me "NO." I want to get "YES." They're both a's so I don't understand why it says they are not the same. Thanks in advance.
     
  2. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    You need to use the isEqualToString: method, not ==. == will compare the pointers, not the contents.

    -Lee
     
  3. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #3
    You're comparing the pointer values of each object, instead of the contents of each object. Use this instead:
    Code:
    if ([str2 isEqualToString:@"a"])
    Edit: Lee beat me ;)
     
  4. thread starter macrumors newbie

    Joined:
    Feb 28, 2009

Share This Page