i’m confusing about nil in objective-C, cause apple said that it’s ok to send a message to a nil object.
so suppose this code :
Foo * myFoo;
[myFoo doSomeStuff];
in Xcode this doesn’t crash so why? does unallocated pointer in objective-C is the same as nil.
Thanks.
Because there’s a difference between
nilandrandom garbage. You see, this line:does not make any guarantee for the value of
myFooif you don’t explicitly set one. Try for yourself:It is likely that it won’t print
0; instead, it will print the last thing that happened to be at that memory location. (It might be zero. But it very well may not be.)Local variables have an undefined value before you assign them one by yourself. The Objective-C runtime will let calls to
nilwork, butnilis strictly defined to be zero: therefore, you have to initialize your variables tonilto use this feature (otherwise, you’re likely to get a segmentation fault, because messaging a random address isn’t good for your program).This will always “work” (by “work” I mean not crash):
Here is an example program that, with my machine, consistently doesn’t have zeroed pointers: