Overview
nil is ObjC’s null, which means that the pointer to the object doesn’t really point to anything. This is usually when you haven’t created the object.
However, in ObjC, nil is much more useful than in other languages. In languages like Java, if an object is null and you try to do pretty much anything with it, it will fail at runtime. nil is a lot more flexible.
In ObjC, you can send nil as a parameter for a selector(that’s how methods are called on ObjC, will use that from now on), receive nil from one, and even call a selector on nil.
Why is this useful?
This is useful mostly to avoid checking if the object you got is nil every time you get an object, or before you call a selector on an object you are not sure. If you have some complex code which doesn’t always initialize objects before sending messages to them, you don’t have to worry on checking if the object is nil or not.
(You can even call something directly on “nil”, like this [nil setText:aText];, though it will give you a warning, and it isn’t useful at all
)
Sometimes you’ll receive nil, and you don’t have to check that object before sending it to another object. For example, if you want to get a song lyrics and then send it to an UILabel, you can just send it without checking it, and it won’t crash.
Another cool thing you can do with nil, and objects in general, is using them as BOOLs. If you need to know if an object is nil (for example, before initializing it (under some circumstances)), you can do if(anObject){}, and if anObject is different from nil, it will happen, if the object is nil, it won’t.
What do I get when the selector I call should return something, but I call it on a nil object?
When the selector you call is supposed to return something, and the object you call it on is nil, it will return some defaults:
- nil if the return type is an object.
- 0/0.0 if the return type is an integer/float/double.
- NO if the return type is BOOL.
- If the return type is a struct, it will fill it’s fields with the above rules.
Things you should look for
Releasing an object will not set it to nil. If you release an object that might get called in the future, and you are not gonna initialize it right away, you can do anObject = nil; to make sure that if you send a message to it, it doesn’t fail.
You shouldn’t take your nil habits to other languages, because chances are that the language won’t support it and it will fail
.





