PDA

View Full Version : question about objective-c: comparing strings to substrings.




ausername
Feb 28, 2009, 12:31 PM
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.



lee1210
Feb 28, 2009, 12:47 PM
You need to use the isEqualToString: method, not ==. == will compare the pointers, not the contents.

-Lee

kainjow
Feb 28, 2009, 12:47 PM
You're comparing the pointer values of each object, instead of the contents of each object. Use this instead:
if ([str2 isEqualToString:@"a"])

Edit: Lee beat me ;)

ausername
Feb 28, 2009, 12:59 PM
Thanks!