Reputation: 104065
I’m implementing -isEqual:
for my custom class. The equality is based on the property values, ie. if all properties are equal, the objects are considered equal. Together with the traditional class check the code looks like this:
- (BOOL) isEqual: (id) object
{
return [object class] == [self class]
&& [[object someProperty] isEqual:someProperty]
&& [[object otherProperty] isEqual:otherProperty];
}
But this fails for nil
property values, ie. two objects of the class having nil
values stored in someProperty
are considered non-equal, whereas I would like them to be equal. Thus I arrived at the following version:
- (BOOL) isEqual: (id) object
{
#define equals(a, b) ((a == b) || ([a isEqual:b]))
return equals([object class], [self class])
&& equals([object someProperty], someProperty)
&& equals([object otherProperty], otherProperty);
}
This seems to work fine. Is this the “standard” way to solve the equality? Seems overly complex to me.
Upvotes: 2
Views: 138
Reputation: 5558
isEqual:
is very much object-specific. It's a semantic equality. It is up to you to define for every class what isEqual means. Thus there is no standard way to do it.
The simplest implementation is return self == object
, your second implementation is very generic and nice, but not necessarily well suited to every class. Per example, for a Person
, comparing the emails could be sufficient, or the emails and first names if you suppose an email could be used by several family members.
Upvotes: 2