How to check for Nil

后端 未结 4 1161
日久生厌
日久生厌 2021-01-21 13:05

I am currently studying objective-c and the basic c programming language.

I have a questions about a particular line of code:

if (!balance)
相关标签:
4条回答
  • 2021-01-21 13:41

    First you need to understand how if works. Basically, any non-zero value is treated as true and a zero value is treated as false.

    Something as simple as if (10) will be treated as true while if (0) is treated as false.

    Any expression evaluates to either a value of zero or a non-zero value.

    An object pointer is just a number - a memory address. A nil pointer is simply an address of 0. Any non-nil pointer will have a non-zero address.

    The ! operator negates that state. A non-zero value will be treated as a zero value and visa-versa.

    So now combine all of this.

    Foo *bar = nil;
    if (bar) // false since bar is nil (or zero)
    
    Foo *bar = [[Foo alloc] init]; // some non-nil value
    if (bar) // true since bar is non-zero
    
    Foo *bar = nil;
    if (!bar) // true since !bar mean "not bar" which is "not zero" which is "non-zero"
    
    Foo *bar = [[Foo alloc] init]; // some non-nil value
    if (!bar) // false since !bar mean "not bar" which is "not non-zero" which is "zero"
    
    0 讨论(0)
  • 2021-01-21 13:45

    In Objective-C, nil is roughly analogous to 0, NULL or false, but for object pointers. In an if statement, it will behave the same as one of the aforementioned scalar values. For example, the following two if statements should produce the same results:

    NSNumber *balance = nil;
    
    if (!balance) {
        // do something if balance is nil
    }
    
    if (balance == nil) {
        // do something if balance is nil
    }
    
    0 讨论(0)
  • 2021-01-21 13:58

    If balance is nil then it will be a pointer to 0x0. That address is never used for a valid object.

    In C anything within an if that evaluates to zero is considered a negative response, anything that evaluates to non-zero is a positive response.

    Pointers evaluate to their address — exactly as if you cast them to an integral type. The ! means "NOT".

    So the test is if(address of balance is not zero).

    0 讨论(0)
  • 2021-01-21 14:01

    NSLog should return (null) (which probably is description for nil), not NULL in console. Your check should look like this:

     if (!controller) 
     {
         // do some stuff here
     }
    
    0 讨论(0)
提交回复
热议问题