I am currently studying objective-c and the basic c programming language.
I have a questions about a particular line of code:
if (!balance)
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"
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
}
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)
.
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
}