iPhone SDK:请解释为什么“nil ==”与“== nil”不同
我已经编写 iPhone SDK 大约 6 个月了,但对一些事情有点困惑......其中我在这里问:
为什么以下内容被认为是不同的?
if (varOrObject == nil)
{
}
vs
if (nil == varOrObject)
{
}
来自 Perl 背景,这让我感到困惑...
有人可以解释为什么如果两个例程在代码中一个接一个地放置,那么两个例程(第二个)中的一个为真,而第一个则不然。两个 if
语句之间的 varOrObject
不会发生变化。
没有具体的代码发生这种情况,只是我在很多地方读到这两个语句不同,但不知道为什么。
提前致谢。
I have been programming iPhone SDK for around 6 months but am a bit confused about a couple of things...one of which I am asking here:
Why are the following considered different?
if (varOrObject == nil)
{
}
vs
if (nil == varOrObject)
{
}
Coming from a perl background this is confusing to me...
Can someone please explain why one of the two (the second) would be true whereas the first would not if the two routines are placed one after the other within code. varOrObject
would not have changed between the two if
statements.
There is no specific code this is happening in, just that I have read in a lot of places that the two statements are different, but not why.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
仅当“==”运算符重载时,它们才会不同。
假设有人为列表重新定义了“==”,以便检查两个列表的内容而不是内存地址(就像Java中的“equals()”)。现在,理论上同一个人可以定义“emptyList == NULL”现在
(emptyList==NULL) 为 true,但 (NULL==emptyList) 仍为 false。
They can only be different if the "==" - Operator is overloaded.
Let's say someone redefines "==" for a list, so that the content of two lists is checked rather than the memory adress (like "equals() in Java). Now the same person could theoretically define that "emptyList == NULL".
Now (emptyList==NULL) would be true but (NULL==emptyList) would still be false.
如果建议您使用后者,那是因为如果您不小心输入
=
,则后者更容易被捕获。否则,它们是相同的,你的书就是错误的。if it's a recommendation that you use the latter, it's because the second is easier to catch if you accidentally type
=
. otherwise, they are identical and your book is wrong.它们完全一样,只是风格不同。如果其中一个是假的,那么另一个就永远不会是真的。
They are exactly the same, it is just a style difference. One would never be true if the other is false.
如果您使用 Objective-C++ 并且覆盖对象的“==”运算符,它们可能会有所不同。
They might be different if you are using Objective-C++ and you were overriding the '==' operator for the object.
他们是一样的。你读到的可能是说如果你错误地将
==
写成=
,前者会将值赋给变量,而if
条件将为 false,而后者将是编译时错误:后者使您有机会在编译时纠正错误。
They are the same. What you have read is probably talking about if you mistakenly write
==
as=
, the former will assign the value to the variable and theif
condition will be false, while the latter would be a compile time error:The latter gives you the chance to correct the mistake at compile time.