Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare objects in Objective-C?

Tags:

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?

like image 801
TalkingCode Avatar asked May 18 '09 09:05

TalkingCode


People also ask

How do you compare objects in Objective C?

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.

How do you compare objects with objects?

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)

How do you compare equality of objects?

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.

Which function is used to comparing the objects?

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.


Video Answer


1 Answers

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.

like image 98
Rob Napier Avatar answered Oct 18 '22 00:10

Rob Napier