tags:

views:

1330

answers:

2

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).

+3  A: 

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 being sent compare: is a NSString, eg:

[@"testString" compare: testString] == NSSOrderedSame]

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

Benedict Cohen
This is a really bad idea! NSString compare documents its parameter as "This value must not be nil". So that could well crash or do other undesirable things if testString is nil.
Peter N Lewis
+4  A: 

Probably [anObject aString] returns nil, sending nil a message returns 0, and 0 == NSOrderedSame.

Tobias