发送 isEqual: 到 nil 总是返回 NO
如果你发送 isEqual: 到一个恰好为零的对象,你总是得到 NO 返回。
这是预期的行为吗?为了成为一个功能而不是一个错误,如果另一个对象也为零,我希望它返回 YES,否则返回 NO?从语义上讲,这似乎是正确的行为。
如果我的期望不正确,建议的步骤是什么?在发送 isEqual: (和朋友)之前检查 nil 吗?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是预期的行为。任何 nil 消息都会返回一个结果,该结果相当于所请求类型的 0。因为布尔值的 0 是 NO,所以这就是结果。
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.
这是 Objective-C 的预期行为。这基本上意味着这样做的
结果是“否”。尽管它没有意义,但当你看它时 - 尽管它很烦人 - 能够向 nil 发送消息实际上是 Objective-C 真正酷的事情之一。有时可以节省大量代码。
我的解决方案是在方便的地方定义这个宏
所以当我需要测试两个对象是否相等:
或不相等时:
希望这会有所帮助。
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.
这是预期的,原因有两个:(1) 在 Objective-C 中,向
nil
发送消息总是返回 false-y 值 (nil
,NO< /code>、
0
、0.0
等;或者更一般地说,0
,可以根据预期的返回类型进行解释方法); (2)nil
表示未知值,两个未知值不一定相等。如果您想查看某个对象是否为
nil
,请使用if (!obj)
或if (obj == nil)
。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)
.