Search code examples
objective-ccocoansstringequalitynsnumber

Comparing nil properties in isEqual


EDIT

From the initial answers, I wasn't clear enough. I just want to check equality between objects of my own custom class, with the result dependent on its properties (pretty standard I believe)? The bit I'm struggling with is making sure a property is treated as equal when both instances have nil for that property.

END EDIT

I want objects of my custom class to return YES for isEqual whenever all of its properties are the same as those of the object passed as the argument. This should include when both properties are nil. I recently learned that [nil isEqual:nil] returns NO.

Will the below implementation achieve what I am looking for?

- (BOOL)isEqual:(id)object
    {
       if (object == self)
            return YES;
        if (!object || ![object isKindOfClass:[self class]])
            return NO;

        return (
            (!object.numberProperty && !self.numberProperty) || (object.numberProperty && self.numberProperty && [object.numberProperty isEqualToNumber:self.numberProperty])
            &&
            (!object.stringProperty && !self.stringProperty) || object.stringProperty && self.stringProperty && [object.stringProperty isEqualToNumber:self.stringProperty])
        ...etc
        );
    }

I am trying to return YES when both properties are nil and also avoid sending isEqualToNumber or isEqualToString to nil.

For BOOLs I would guess that this is not necessary since a BOOL can't be nil - will a simple == suffice for booleans?

Anything I'm missing, or any ways to improve this?


Solution

  • Since you can't (ok, it's just not a good idea) override isEquals for all object types including nil, the obvious choice is to just make a separate simple function for the times you need it;

    BOOL nilEqual(id a, id b)
    {
        return (a == nil && b == nil) || [a isEqual:b];
    }