Comparing objects in Obj-C

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.

Leave a Comment