I've been reading some ebooks about cocoa, so I can learn more, but I don't have so cl开发者_StackOverflow社区early what this types of "if" mean:
if(!something)
if(something)
And I suppose that:
if (something !=nil)
Means that if something doesn't exists, right?
Thanks :)
In C everything un-equal NULL
or 0
is considered true
.
Thus
if (!something)
is identical to
if (!(something != nil))
and thus identical to
if (something == nil)
in case of Objective-C objects (as nil
is basically NULL
).
So if (something)
is basically a short-hand for if (something != nil)
.
And if (!something)
is basically a short-hand for if (something == nil)
.
For non Objective-C pointers you could just replace nil
with NULL
. (nil
is more or less only syntax sugar anyway.)
You can also use this to check if an integer is un-equal 0
:
As such the condition if ([myArray count])
is true
unless myArray
is empty.
Assuming that something is a pointer to an NSObject.
if(something)
This returns YES if something is a non-nil pointer
if(!something)
This returns YES if something is nil. This in this case because something
is nil, and !
(the not operator) inverts this to become true,
if(something)
is the same as if(something != nil)
. But most programmers I know think this is a tautology and prefer the shorter expression.
While I'm at it - you may see this written as if(nil != something)
. The reason for this is that if, by accident you write =
instead of !=
this will raise an error as you can't set a value to nil, but if it was the other way around and you mis-wrote the condition, it would set the value of something to nil, which may not be what you want to do.
This is general syntax for most C-based languages. What you need to realize is that the if statement checks the expression in the parantheses to be false(zero) or true(1 or non-zero). So, when you say "if(something)", you're basically asking if to check if it's: 1. true or false(for Boolean expressions); 2. Zero or non-zero (for arithmetic expressions); 3. Null or valid address (for pointers, strings, etc).
Now you need to remember that the "!" operator is used to negate an expression i.e. Bitwise change every "0" bit in the result to a "1" and vice versa. So, basically you're checking if the negative of the result is true or non-zero.
In short, you use "if(something)" when you want the code snippet to execute when "something" is true or non-zero. You use "if(!something)" when you want your code snippet to execute when "something" is false or zero.
精彩评论