Most of the examples I found on the net write this:
if(x != nil)
// ...
Is there any problems with this?
if(x)
// ...
I tried both in a simple program and couldn’t found any difference.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In Objective-C,
nilis defined as a value called__DARWIN_NULL, which essentially evaluates to0orfalsein if-statements. Therefore, writingif (x == nil)is the same as writingif (!x)and writingif (x != nil)is equal toif (x)(since comparing tofalsecreates a negation, and comparing totruekeeps the condition the same).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.It’s like comparing
if (someCondition == true)versusif (someCondition).It all depends on you, and who’s going to be reading the code.
Edit: 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
someConditionin the example above were to evaluate to an integer value of, say, -1, comparing it totruewould result infalse, and the if-statement would not be evaluated. Something to be aware of.