Monday, March 26, 2012

isEqual: vs. isEqualToString: vs. compare:

Mark Dalrymple:

The conclusion I draw at this point is that your choice of isEqual: and isEqualToString: is purely stylistic. If you have a lot of isEqual: calls in a method comparing other objects, go ahead and use isEqual:. If you want to tell the reader that you’re only expecting strings to be involved, use isEqualToString:. I believe that the demonstrated corner case makes any safety benefits moot in choosing which method to use.

The main point I would emphasize is the need to check for nil before using compare:, because if the receiver is nil you’ll always get NSOrderedSame. I like to use category methods such as mjtCaseInsensitiveIsEqual: where the result from a nil receiver will be what you expect.

Update (2012-03-30): Dalrymple has a follow-up post.

Comments RSS · Twitter

Leave a Comment