isEqual vs. ==


#1

Can someone provide some details to clarify this part of the text:
The first steps through the collection asking each object “isEqual:anObject?” The second steps through the collection asking each object “== anObject”?

It seems like isEqual:anObject ends up using ==. Note, I understand the difference between equality and identical as illustrated in Fig.24.2.


#2

Hi CA4iOS,

Here’s my take on it. I know you mentioned that you understood 24.2, but hope that its OK to touch on it again to help explain my answer.

For Figure 24.2, think of the difference between “isEqual:anObject” and ‘==’ as the former testing if the characters for the NSStrings are the same, and the latter if their pointers are the same (i.e. they point to the same object/memory address). Extending this idea to the NSMutable array example, “indexOfObject:anObject” is asking if the objects in the array have the same value (i.e. isEqual) and then returns the index in the mutable array where this value first occurred. The “indexOfObjectIdenticalTo:anObject” method is looking through the array to find if the object memory addresses are the same (i.e. ==, they point to the same area of memory) and then returns the index in the mutable array where this memory address was first found.

So simply speaking, “isEqual” is comparing object values (equal), whereas “==” is comparing memory addresses (identical). If an object points to the same memory address as another object then it has the same address and the same value so it is “identical”. However, you can have objects in different parts of memory with different addresses with the same value (like the @“Blorp” in Figure 24.2) so while they are equal, they are not identical.

Hope that helps!
:slight_smile: