Sending isEqual: to nil always returns NO

后端 未结 3 542
栀梦
栀梦 2021-01-02 07:58

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 i

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-02 08:37

    This is expected behaviour from Objective-C. This basically means that doing this

    if ([nil isEqual:nil]) { ... }
    

    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

    #define IsEqual(x,y) ((x && [x isEqual:y]) || (!x && !y))
    

    So when I need to test if two objects are equal:

    if (IsEqual(obj1, obj2)) { ... }
    

    or not equal:

    if (!IsEqual(obj1, obj2)) { ... }
    

    Hope this helps.

提交回复
热议问题