I just started reading the Objective-C tutorials, and there is a section on "sending a message to nil
":
There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to nil may also be valid:
What does this mean? I can't seem to follow it.
The special treatment of nil
means that you can do the following:
SomeClass * someObject;
someObject = nil;
[someObject doSomething];
And you can be assured that nothing will happen.
Now, why is this important?
In Objective-C, sending a message to an object means telling that object to do something, or asking that object for some information. Some examples:
[someObject updateRecords]; // 1
x = [someObject size]; // 2
Line 1 sends someObject
a message called updateRecords
, and line 2 sends the same object a message called size
, which is expected to return a value. These messages boil down to method calls, and the actual code that ends up being run is determined by the Objective-C runtime system, since Objective-C is a dynamically-typed language.
To determine which method to invoke, the runtime system reads information from the address of the object in question (someObject
, in the examples above) to work out what class it is an instance of. Using that information, it is able to look up the appropriate method to call, and when all that has been figured out, it executes the code in the method.
If the runtime system did not treat nil
as a special case, it would probably crash if you tried to execute the code shown at the top. nil
is defined to be zero, so the runtime would start reading information from an address stored at location zero in memory, which is almost gauranteed to be an access violation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With