Why do NSString comparisons: return NSOrderedSame when the strings are different?

Why 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 will no longer repeat this error (hence the immediate answer).

+3
source share
2 answers

This is due to what testStringmay equal nil. Sending a message in nilreturns nil. NSOrderedSameequal 0and 0equal 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, make sure that before comparing the object is not nil, for example:

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

NB: I added this question so as not to repeat this error again.

+9
source

, [anObject aString] nil, nil 0 0 == NSOrderedSame.

+5

Source: https://habr.com/ru/post/1710173/


All Articles