NSArray containsObject method

The documentation for [NSArray containsObject:] says:

This method determines whether
anObject is present in the receiver by
sending an isEqual: message to each of
the receiver’s objects (and passing
anObject as the parameter to each
isEqual: message).

The problem is that you are comparing references to objects rather than the values of the objects. To make this specific example work, you will either need to send [collection containsObject:] an instance of a variable it contains (e.g. A, B, or C), or you will need to override the [NSObject isEqual:] method in your Item class.

This is what your isEqual method might look like:

- (BOOL)isEqual:(id)other {
    if (other == self)
      return YES;
    if (!other || ![other isKindOfClass:[self class]])
      return NO;
    if (self.length != other.length || self.width != other.width || self.height != other.height)
      return NO;
    return YES;
}

For a better implementation, you may want to look at this question.

Leave a Comment