Ben Packard
Ben Packard

Reputation: 26476

Testing NSNumber for nil in isEqual

I have a custom isEqual to test for equality between objects of my class:

BOOL result = ([attempt.attemptId isEqualToNumber:self.attemptId] &&
        [attempt.pitcher isEqualToString:self.pitcher] &&
        [attempt.vsTeam isEqualToString:self.vsTeam] &&
        attempt.isHomeTeam == self.isHomeTeam &&
        [attempt.hitlessInnings isEqualToNumber:self.hitlessInnings] &&

...etc

return result;

Occasionally any of these properties might be nil. When a string is nil, equality seems to work as expected. But isEqualToNumber for NSNumber objects fails entirely:

[NSNull isEqualToNumber:]: unrecognized selector sent to instance 0x1896678'

How can I test for nil in isEqual and return YES when both objects have nil for that property?

Upvotes: 0

Views: 1769

Answers (1)

Wain
Wain

Reputation: 119031

Generally when writing an equality method you should:

  1. Check the class of the object being compared first
  2. Check the local object and the compared object properties for nil
  3. Check the local object and the compared object properties for equality

If you are being passed NSNull instead of nil then that is an error in your JSON handling and validation which needs to be fixed. You also need to check the nil case explicitly as nil == nil is true but [nil isEqual:nil] is false.

Upvotes: 1

Related Questions