How to check for Nil

2020-04-16 03:31发布

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

I have a questions about a particular line of code:

if (!balance)

Balance is an object that is created. I understand that this code is checking to see if the object balance is nil or not, is this correct?

Could somebody please explain how exactly the code checks for nil? Does it return 0 if the value of balance is nonzero and 1 if the value is 0?

Thanks in advance.

4条回答
三岁会撩人
2楼-- · 2020-04-16 03:59

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"
查看更多
家丑人穷心不美
3楼-- · 2020-04-16 04:00

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
}
查看更多
虎瘦雄心在
4楼-- · 2020-04-16 04:02

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
 }
查看更多
Root(大扎)
5楼-- · 2020-04-16 04:13

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

查看更多
登录 后发表回答