Possible Duplicate:
ObjectiveC: if (obj) {…} AND if (obj != nil) {…}, which is better?
Is there a difference between these two conditions:
if (!object) {
// do something
}
and . . .
if (object == nil) {
// do something
}
Possible Duplicate:
ObjectiveC: if (obj) {…} AND if (obj != nil) {…}, which is better?
Is there a difference between these two conditions:
if (!object) {
// do something
}
and . . .
if (object == nil) {
// do something
}
No, there is no difference. Both of those examples are exactly the same. From the C spec 6.5.3.3 Unary arithmetic operators:
The result of the logical negation operator
!
is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has typeint
. The expression!E
is equivalent to(0==E)
.
Since nil
is 0, that last sentence applies exactly.
If object is of type id
or any valid Objective-C object, then only one difference is present: readability. (i. e. from the compiler's point of view, they're both the same.)
However, there may be examples when comparing to nil
wouldn't be very nice. For example, if for some evil illogocal reason, object was an int
, only the two following statements would be valid:
if (object == 0)
and
if (!object)
and they would again be equivalent, but comparing an int to a pointer (which nil
is) - except if the integer is an explicit constant 0 - is illegal and most likely result in a compiler warning (in most cases, it would still work, however...)