How to check for Nil

后端 未结 4 1162
日久生厌
日久生厌 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"
    

提交回复
热议问题