Feb 12

It is a good practice to set a variable to nil after you release it:

[myVariable release], myVariable = nil;

If you don’t do this then you may experience bugs that are difficult to track down. Say that you inadvertently refer to myVariable after it has been released. Sometimes the memory pointed to by myVariable still has the old content of your object, and your app will run fine. Sometimes that memory location has been overwritten with something else, and you’ll get an unpredictable result.

One nice characteristic of Objective-C is that you can send messages to nil objects without error. (Unlike Java, for example, where NullPointerException is probably the most common exception thrown.) So if you have set myVaraible to nil and you then try to send a message to it with [myVariable something] then it will not fail. Nothing will happen of course, but at lest nothing will happen every time, which is much easier to track down than indeterministic behavior.

One might argue that sending a message to a nil object is the result of faulty code. Your code should know if an object is valid or nil. But here’s a simple counter-example:
If your class has properties with a retain declaration, then you should release those properties in the dealloc method. In many cases setting the value of a property to nil is perfectly valid. And thus sending release to that nil property in dealloc should be ok.

Keep in mind that the above conventions apply to Objective-C. If you’re calling Core Foundation functions you need to be more careful when dealing with nil.

For example, if you call the following function with a nil parameter, it will fail:

CFRelease(contactFirstName);

Before calling CFRelease you need to check the parameter value like this:

if (contactFirstName) CFRelease(contactFirstName);

written by Nick \\ tags: , ,