How do I compare two objects of a custom class? My idea was to add an additional method to the class in which I can compare the current object with another object of the same kind.
So I can write my own code how each field of the class is compared.
This is how I would do it. Or are there some predefined methods to do that? Like "isEqualTo" of the NSString class?
When you use the == operator to compare two objects in Objective-C, you're checking to see if they point to the same location in memory. NSObject and NSValue have different semantics for equality, and understanding the difference between them is the key to understanding how equality works in most programming languages.
The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)
The behavior for performing loose equality using == is as follows: If the operands have the same type, they are compared as follows: Object: return true only if both operands reference the same object. String: return true only if both operands have the same characters in the same order.
When using the comparison operator ( == ), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values (values are compared with == ), and are instances of the same class.
The pointers to -isEqual:
are good, but if you implement -isEqual:
, you absolutely must also implement -hash
in such a way that if two objects return YES
for -isEqual:
they will also return the same value for -hash
. Implementing isEqual:
without also implementing -hash
leads to some very surprising bugs when you use Collections like NSArray.
For new developers, I tend to recommend against overloading -isEqual:
. I recommend instead using the same technique as NSString, and create a custom -isEqualToFoo:
(where Foo
is your class) until you understand the impact of -isEqual:
on collections and specifically want this behavior. Overloading -isEqual:
powerful, but the bugs you can create are subtle. Creating your own custom comparator is safer and clearer in many cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With