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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With