44

What on earth is the difference between these methods?

lbrndnr
  • 3,361
  • 2
  • 24
  • 34
  • 2
    Some quick searchin revels similar threads where people have discussed this kind of thing gin depth http://stackoverflow.com/questions/1112373/implementing-hash-isequal-isequalto-for-objective-c-collections – Paul.s Aug 17 '11 at 17:09

2 Answers2

43

isEqual: is part of the NSObject protocol and is meant for comparing objects.

isEqualTo: is part of the Cocoa AppleScript support infrastructure (specifically, NSComparisonMethods, which allow AppleScript to compare Cocoa objects). It's normally the same as isEqual:, but can be overridden if you want equality to work differently internally and in a script.

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • What a trap :( I overwrote `isEqual(to:)` by accident, and has a test failure that took me a while to catch. – Alexander May 31 '20 at 13:23
7

isEqualTo: is part of the NSComparisonMethods informal protocol, which also contains methods like isGreaterThan: and isNotEqualTo:, and is used for scripting support. And:

The default implementation for this method provided by NSObject returns YES if an isEqualTo: message sent to the same object would return YES.

So when sending this message to an NSObject (or any subclass which does not override it) you will get the same behavior as isEqual:, however, you should be using isEqual: instead.

jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • 5
    The documentation for `isEqualTo:` doesn't say that it's equivalent to `isEqual:`; it says that it's equivalent to sending `isEqualTo:` to the other object. It doesn't actually promise to use `isEqual:`, although I'm pretty sure it does. (Still, safer to just use `isEqual:` directly.) `isEqualTo:` is not merely “commonly used for scripting support”: That whole protocol *exists* for scripting support. It is commonly used for non-scripting purposes where `isEqual:` would be the more proper method. – Peter Hosey Aug 17 '11 at 17:25
  • 1
    It does say that the default implementation uses `isEqual:`. – jtbandes Aug 17 '11 at 17:27
  • 1
    Read it again. It says it uses `-isEqualTo:`. ;) Though I think that's just a typo. – Jonathan Grynspan Aug 17 '11 at 17:32