Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing objects in Obj-C

Tags:

objective-c

How does one compare objects in Objective-C?

Is it as simple as == ?

I want to check an array for an object and if it doesnt exist add it to the array otherwise, remove it from the array.

like image 590
some_id Avatar asked Feb 20 '11 01:02

some_id


3 Answers

Comparing objects in Objective-C works much the same as in Java or other object-oriented languages:

  • == compares the object reference; in Objective-C, whether they occupy the same memory address.
  • isEqual:, a method defined on NSObject, checks whether two objects are "the same." You can override this method to provide your own equality checking for your objects.

So generally to do what you want, you would do:

if(![myArray containsObject:anObject]) {
    [myArray addObject:anObject];
}

This works because the Objective-C array type, NSArray, has a method called containsObject: which sends the isEqual: message to every object it contains with your object as the argument. It does not use == unless the implementation of isEqual: relies on ==.

If you're working entirely with objects that you implement, remember you can override isEqual: to provide your own equality checking. Usually this is done by comparing fields of your objects.

like image 100
Tim Avatar answered Oct 26 '22 08:10

Tim


Every Objective-C object has a method called isEqual:.

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isEqual:

So you would want to override this for your custom object types.

One particular important note in the documentation:

If two objects are equal, they must have the same hash value. This last point is particularly important if you define isEqual: in a subclass and intend to put instances of that subclass into a collection. Make sure you also define hash in your subclass.

like image 11
vdsf Avatar answered Oct 26 '22 08:10

vdsf


== will compare the pointer, you need to override

- (BOOL)isEqual:(id)anObject
like image 4
CiNN Avatar answered Oct 26 '22 10:10

CiNN