在Objective-C中测试nil-if(x!= nil)vs if(x) [英] Testing for nil in Objective-C -- if(x != nil) vs if(x)
问题描述
我在网上找到的大多数示例都这样写:
Most of the examples I found on the net write this:
if(x != nil)
// ...
这有什么问题吗?
if(x)
// ...
我在一个简单的程序中都尝试过,但没有发现任何区别.
I tried both in a simple program and couldn't found any difference.
推荐答案
在Objective-C中,nil
定义为名为__DARWIN_NULL
的值,其在if语句中的值实际上为0
或false
.因此,写作
if (x == nil)
与写if (!x)
相同,写if (x != nil)
等于if (x)
(因为与false
比较会产生否定,与true
进行比较会保持相同的条件).
In Objective-C, nil
is defined as a value called __DARWIN_NULL
, which essentially evaluates to 0
or false
in if-statements. Therefore, writing
if (x == nil)
is the same as writing if (!x)
and writing if (x != nil)
is equal to if (x)
(since comparing to false
creates a negation, and comparing to true
keeps the condition the same).
您可以以任何一种方式编写代码,而这实际上取决于您认为可读性更高的代码.我发现if (x)
更有意义,但这取决于您的风格.
You can write your code either way, and it really depends on which you think is more readable. I find if (x)
to make more sense, but it depends on your style.
这就像比较if (someCondition == true)
与if (someCondition)
.
这一切都取决于您,以及谁来读取代码.
It's like comparing if (someCondition == true)
versus if (someCondition)
.
It all depends on you, and who's going to be reading the code.
正如Yuji正确提到的那样,由于Objective-C是C的超集,因此任何求值为0以外的值的条件都被认为是真实的,因此,如果someCondition
在上面的示例中,计算结果为整数值-1,将其与true
进行比较将得出false
,并且不会评估if语句.要注意的事情.
As Yuji correctly mentions, since Objective-C is a superset of C, any condition that evaluates to a value other than 0 is considered to be true, and therefore, if someCondition
in the example above were to evaluate to an integer value of, say, -1, comparing it to true
would result in false
, and the if-statement would not be evaluated. Something to be aware of.
这篇关于在Objective-C中测试nil-if(x!= nil)vs if(x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!