If you send isEqual: to an object that happens to be nil, you always get NO back.
Is this the expected behavior? To be a feature instead of a bug, I would expect it to return YES if the other object is also nil, and NO otherwise? Semantically this seems the correct behavior.
In case my expectations are incorrect, what the recommended proceedure? Check for nil before sending isEqual: (and friends)?
It is expected, for two reasons: (1) in Objective-C, sending a message to
nil
always returns a false-y value (nil
,NO
,0
,0.0
, etc.; or, more generally speaking,0
, which can be interpreted based on the expected return type of the method); (2)nil
represents an unknown value, and two unknown values are not necessarily equal to each other.If you want to see if an object is
nil
, useif (!obj)
orif (obj == nil)
.Yes, this is the expected behavior. Any message to nil will return a result which is the equivalent to 0 for the type requested. Since the 0 for a boolean is NO, that is the result.
This is expected behaviour from Objective-C. This basically means that doing this
evaluates to NO. Even though it doesn't make sense, when looking at it - and even though it's annoying - being able to send messages to nil is actually one of the really cool things about Objective-C. Saves you a lot of code sometimes.
My solution is to define this macro somewhere handy
So when I need to test if two objects are equal:
or not equal:
Hope this helps.