I'm testing a string with an other, and I notice that if the first string is nil, the return value equals NSOrderedSame (valued to 0).
if([oneString compare:otherString] == NSOrderedSame)
returns YES if oneString is nil.
So I should test
if(oneString != nil && [oneString compare:otherString] == NSOrderedSame)
I guess I should also test otherString in the condition, and make a special case if I want that [nil compare:nil]
returns NSOrderedSame
.
Is there a more convenient way to compare string without having to do such tests and to really test if both strings are the same ?
You can try
[someString isEqualToString:@"someOtherString"];
Or for case insensitive:
[[someString lowerCaseString] isEqualToString:[otherString lowerCaseString]];
I would use the approach @seretur suggests unless you are worried about case. In that case, I'd use caseInsensitiveCompare:
which is similar to the compare:
method you are currently using.
You can also simplify that if statement like so:
if (oneString && [oneString caseInsensitiveCompare:otherString] == NSOrderedSame) { ...
According to the documentation, the string must not be nil. If it is, it can result in quirky behavior.
It is absolute legal to send something to nitl. But by definition it will always return nil. and nil itself actually is 0.
If we now look at NSComparisonResult
, NSOrderedSame
is 0 too.
enum {
NSOrderedAscending = -1,
NSOrderedSame,
NSOrderedDescending
};
typedef NSInteger NSComparisonResult;
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