Sunday, November 23, 2008

(BOOL)isEqual:(id)anObject

In NSObject, this method is defined to return YES if and only if the receiver and anObject are the same object—that is, if both are pointers to the same memory location.

Clearly, this is not always the equal that you would hope for, so this method is overridden by many classes to implement a more appropriate idea of equality. For example, NSString overrides the method to compare the characters in the receiver and anObject. If they have the same characters in the same order, the two strings are considered equal.

Thus, if x and y are NSStrings, there is a big difference between these two expressions:

x == y


and

[x isEqual:y]


The first expression compares the two pointers. The second expression compares the characters in the strings. Note, however, that if x and y are instances of a class that has not overridden NSObject's isEqual: method, the two expressions are equivalent.

No comments: