Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between NSString compare: and isEqual(ToString):?

Occasionally I find code which tests if two NSStrings are the same like this:

if ([str1 compare:str2] == NSOrderedSame) {
    // Do something
}

Now, I believe this is less readable than using isEqualToString: and it also has some nasty side effects, like if str1 == nil the if(..) evaluates to true, or when str2 == nil havoc might break upon us according to the Apple docs. (Edit: As hatfinch points out, if str1 == nil && str2 == nil both variants produce the wrong result. So you need to guard yourself against this case anyway).

But before I crusade against those statements in my companys code, I wanted to make sure I didn't miss some important point.

So my question basically boils down to: Is there any difference between a compare: to NSOrderedSame and isEqual:?

like image 562
Alfonso Avatar asked May 20 '10 20:05

Alfonso


1 Answers

Reading the docs, the only differences I can find that you haven't already mentioned are:

  1. isEqualToString: first compares the id of the two strings, which is a potential speed gain in an application that makes frequent re-use of strings. From the NSString reference:

    Return Value:
    YES if aString is equivalent to the receiver (if they have the same id or if they are NSOrderedSame in a literal comparison), otherwise NO.

  2. isEqualToString: is really more analogous to compare: options:NSLiteralSearch, as can be seen in the above quote. NSLiteralSearch is more finicky about Unicode character representation:

    “Literal” when applied to string comparison means that various Unicode decomposition rules are not applied and Unicode characters are individually compared. So, for instance, “Ö” represented as the composed character sequence “O” and umlaut would not compare equal to “Ö” represented as one Unicode character.

This is really just nitpicking compared with the false positives and undefined behavior mentioned in your question.

Source: NSString Class Reference

like image 148
Endemic Avatar answered Sep 20 '22 21:09

Endemic