Testing for nil in Objective-C -- if(x != nil) vs if(x)

objective-c nil vs null
check for null objective-c
nil vs null swift
objective-c set object to nil
objective-c check null object
difference between nil and nil
nil in c
nsnull swift

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.

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).


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) versus if (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 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.

How to check if an object is nil in Objective-C?, Numeric operators are written so that if they don't know the type of the righthand Returning to our example of adding a Fixnum and a Rational, the coerce method of Suppose you want to test whether the variable x is nil or not. if x != nil # Expression "x != nil" returns true or false to the if puts x # Print x if it is defined end  Stack Overflow Public questions and answers; Teams Private questions and answers for your team; Enterprise Private self-hosted questions and answers for your enterprise; Talent Hire technical talent

Both

if (x != nil)

and

if ( x )

are equivalent, so pick the variant that in your opinion makes your code more readable for you (and others who will read and support your code)

The Ruby Programming Language, (Continued) R29: (\exists Tobj; f1 && x==obj && f2(obj)) ↩→ (f1 && x instanceof type of x is equal to T R34: (x != null) ↩→ true if x is statically known to be non-​null corresponds to membership semantics3: E(rlift(obj))c ⇐⇒ ∃e ∈r: lift(obj)(e​)  In modern OS X and iOS SDKs: nil and Nil and NULL are identical in Objective-C and in Objective-C++ before C++11. nil and Nil and std::nullptr are identical in Objective-C++ with C++11. Stylistically, many people prefer to use nil for Objective-C objects and NULL or nullptr for other pointer types. I myself now use nil everywhere.

The best and safe way to check nil is Make a common method, and add all these null :

+ (NSString *)trimWhiteSpaceAndNewLine:(NSString *)string {
    NSString *stringSource = [NSString stringWithFormat:@"%@",string];
    if ([stringSource isEqualToString:@"(null)"]) {
        stringSource = @"";
        return stringSource;
    }
    if ([stringSource isEqualToString:@"<null>"]) {
        stringSource = @"";
        return stringSource;
    }
    if ([stringSource isEqualToString:@"<nil>"]) {
        stringSource = @"";
        return stringSource;
    }
    if ([stringSource isKindOfClass:[NSNull class]]) {
        stringSource = @"";
        return stringSource;
    }
    if ([stringSource isEqualToString:@""]) {
        stringSource = @"";
        return stringSource;
    }
    if (stringSource == nil) {
        stringSource = @"";
        return stringSource;
    }
    NSString *stringFinal = [stringSource stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return stringFinal;
}  

And check

NSString *strUuid = [Common trimWhiteSpaceAndNewLine:[dict valueForKeyPath:@"detail.uuid"]];
        if (![strUuid isEqualToString:@""]) {
            // do your stuff
        }

Hardware and Software: Verification and Testing: 10th , This means that if x is nil, you are prevented from using it as though it has a are not well-integrated into the type system (such as C, Objective-C, and Java), code forget to check values or because they find such checking to be too unwieldy. A “cute” feature of Objective-C is that it allows messages to be passed to nil objects, simply returning a zero instead of throwing an exception. This removes the problem with NullPointerException s in Java–or segmentation faults in C/C++–and allows the developer to avoid peppering their code with null checks.

Both are the same and this is a style question and it boils down to whether you prefer:

  1. if (something) { ... }

    versus

  2. if (something != nothing) { ... }

I have always found #1 more clear but #2 is used extensively in documentation and hence the field so it is better to both know both forms and adapt to what a project uses and be stylistically consistent.

Professional Swift, Swift offers up many ways to check if an optional value is currently var someNumber: Int? if someNumber != nil { // Do something. } languages (​including Objective-C) without the need for extensions and such. With the proposed x? sugar this is no longer the case – one may wonder, for example, if the  Objective C is a superset of C programming language. The file extensions normally include .m or .h depending on whether it is a program file or a header file. Head to Head Comparison Between C++ and Objective C (Infographics) Below is the top 9 difference between C++ vs Objective C

A More Swifty Way to Check an Optional for a Nil Value, Objective-C is a powerful and extremely useful language, but it's also a bit dangerous. It is that 0 or 1 , not the value of x , that is compared with 0.5. If there's any chance your code will encounter nil , you must check for and handle it separately before you You should probably stick to the != nil version. Key Differences Between Swift vs Objective C. Let us discuss some of the major difference between Swift vs Objective C: Swift is the latest programming language that is developed by Apple and can be run on various cross-platform operating systems such as Linux, Darwin, Free BSD, etc. whereas Objective C is general-purpose object-oriented programming language used by Apple in its operating

Friday Q&A 2012-12-14: Objective-C Pitfalls, Comparison operators, as their name implies, allow you to compare two values. and they are of the same type. $a != $b, Not equal, TRUE if $a is not equal to $​b after Note: Please note that the null coalescing operator is an expression, and that it Since 'X' or any other string without a number in it converts to 0 when​  Q&A for users of Linux, FreeBSD and other Un*x-like operating systems Stack Exchange Network Stack Exchange network consists of 176 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Comparison Operators - Manual, As it is a class in java.lang package, it is called when we try to perform some operations are case-sensitive in java, we can't write NULL or 0 as in C language. public static void main(String args[]). {. Test obj= null ;. obj.​staticMethod();. obj. and != The comparison and not equal to operators are allowed with null in Java. Nil is for ObjC objects (id), NULL is simply for C pointers. Check out this article with really good explanations - http://nshipster.com/nil/

Comments
  • I should add that if(someCondition==true) is discouraged, because in C-derived languages, any value other than 0 can be in principle regarded as a Boolean true value, but due to historical reasons if someCondition is -1 and true is defined as 1 then someCondition==true evaluates to false.
  • @Yuji, that is correct. I was trying to imply though, that someCondition evaluates to a boolean, but that is an important warning.
  • Check the section "working with nil" in the Apple docs: developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/… . As they say, both forms are fine. However, beware that there subtle and treacherous issues if you try to cast an Obj-C reference to BOOL, as described in mikeash.com/pyblog/…
  • so if x==0; would if(x) and if(x!=nil) behave the same?
  • @erik Yes, they should. nil is essentially equal to 0, so those conditions evaluate to to if (0) and if (0 != 0), both of which are false.