Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone - Comparing a nil NSString with another valued NSString returns NSOrderedSame

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 ?

like image 562
Oliver Avatar asked Mar 29 '11 00:03

Oliver


4 Answers

You can try

[someString isEqualToString:@"someOtherString"];

Or for case insensitive:

[[someString lowerCaseString] isEqualToString:[otherString lowerCaseString]];
like image 142
ferostar Avatar answered Nov 19 '22 22:11

ferostar


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) { ...
like image 30
raidfive Avatar answered Nov 19 '22 21:11

raidfive


According to the documentation, the string must not be nil. If it is, it can result in quirky behavior.

like image 2
FreeAsInBeer Avatar answered Nov 19 '22 22:11

FreeAsInBeer


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;
like image 1
vikingosegundo Avatar answered Nov 19 '22 20:11

vikingosegundo