Sending messages to nil

Nearly all object-oriented languages have the idea of nil, the pointer to no object. In Objective-C, nil is the zero pointer (same as NULL, which was discussed in Chapter 8).

In most object-oriented languages, sending a message to nil is not allowed. As a result, you have to check for non-nil-ness before accessing an object. So you see this sort of thing a lot:

i​f​ ​(​f​i​d​o​ ​!​=​ ​n​i​l​)​ ​{​
 ​ ​ ​ ​[​f​i​d​o​ ​g​o​G​e​t​T​h​e​N​e​w​s​p​a​p​e​r​]​;​
}​

When Objective-C was designed, it was decided that sending a message to nil would be OK; it just wouldn’t do anything at all. Thus, this code is completely legal:

D​o​g​ ​*​f​i​d​o​ ​=​ ​n​i​l​;​
[​f​i​d​o​ ​g​o​G​e​t​T​h​e​N​e​w​s​p​a​p​e​r​]​;​

Important thing #1: If you are sending messages and nothing is happening, make sure you aren’t sending messages to a pointer that has been set to nil.

Important thing #2: If you send a message to nil, the return value doesn’t mean anything.

D​o​g​ ​*​f​i​d​o​ ​=​ ​n​i​l​;​
N​e​w​s​p​a​p​e​r​ ​*​d​a​i​l​y​ ​=​ ​[​f​i​d​o​ ​g​o​G​e​t​T​h​e​N​e​w​s​p​a​p​e​r​]​;​

In this case, daily will be zero. (In general, if you expect a number or a pointer as a result, sending a message to nil will return zero. However, for other types like structs, you will get strange and unexpected return values.)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset