43

What is the difference between these two NSArray methods?

William Jockusch
  • 26,513
  • 49
  • 182
  • 323

3 Answers3

72

indexOfObjectIdenticalTo checks for the exact same id (same address). indexOfObject checks that isEqual: returns YES.

sam-w
  • 7,478
  • 1
  • 47
  • 77
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • 1
    Also note that `indexOfObjectIdenticalTo:` is many orders of magnitude faster than `indexOfObject:`. Although neither is particularly fast. If you want high performance you should consider using `NSSet` – Abhi Beckert Oct 02 '14 at 05:20
18

The first uses isEqual: to find a matching object, while the second looks for the same object (i.e., the object at the same memory location).

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
  • Any way to make it use isEqualToString: instead? – Andrew Nov 16 '13 at 22:43
  • 1
    @SantaClaus: It already does. `isEqual:` and `isEqualToString:` behave identically when you pass an `NSString *`. The only differences between the two are a slight performance advantage and static type checking provided by `isEqualToString:`, which is irrelevant in the context of `indexOfObject:`. – Marcelo Cantos Nov 16 '13 at 23:16
  • @MarceloCantos Hmmm. I have an issue then. :) – Andrew Nov 16 '13 at 23:33
  • @MarceloCantos I'll just make a new question eventually – Andrew Nov 16 '13 at 23:40
  • It's funny how the two answers contradict each other. You say the first checks for equal, while the other guys says the other one checks for the equal function instead of id. – Gilles Lesire Jul 15 '14 at 21:59
  • @GillesLesire: Actually, they're both the same. They just present the cases in a different order. – Marcelo Cantos Jul 16 '14 at 11:16
  • You are right. Skimmed through the answers too fast. – Gilles Lesire Jul 16 '14 at 13:40
2

indexOfObjectIdenticalTo is far more faster than indexOfObject but it uses pointer comparison == instead of calling isEqual:

If you are searching for a pointer match, always use indexOfObjectIdenticalTo to get peak performance

Peter Lapisu
  • 19,915
  • 16
  • 123
  • 179