Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does NSString compare: return NSOrderedSame when the strings are different?

Tags:

objective-c

Why does compare return NSOrderedSame?:

NSString *testString = [anObject aString];

if ([testString compare:@"a string which doesn't equal testString"] == NSOrderedSame) {
    //do stuff
}

NB: I added this question so I won't make this mistake again (hence the immediate answer I gave).

like image 577
Benedict Cohen Avatar asked Dec 06 '22 06:12

Benedict Cohen


1 Answers

This is because testString can equal nil. Sending a message to nil returns nil. NSOrderedSame equals 0, and 0 equals nil.

NSLog(@"nil == NSOrderedSame = %d", (nil == NSOrderedSame)); //nil == NSOrderedSame = 1
NSLog(@"[nil compare:@\"arf\"] == nil = %d", ([nil compare:@"arf"] == 0));    //[nil compare:@\"arf\"] == nil = 1

To avoid this ensure that the object is not nil before comparing, eg:

if (testString != nil && [testString compare:@"testString"] == NSSOrderedSame) ...

NB: I added this question so I wouldn't make this mistake again.

like image 144
Benedict Cohen Avatar answered Jun 03 '23 01:06

Benedict Cohen