views:

86

answers:

4

I see a lot of Objective-C code that has the following syntax when attempting to free objects from memory when they are no longer needed.

[controller release], controller = nil;

Why set the variable to nil after sending the release message? Isn't release going to free the object no matter what? Why does it need to be set to nil as well.

Is this just an "old-school" way of doing things in Obj-C, or is there more to it than I realize?

A: 

Since sending a message to a nil object is a valid operation in Objective-C (nothing happens), setting an object pointer to nil prevents bad things from happening if the object is sent a message after it has been released.

Ferruccio
+1  A: 

Calling release on an object does not necessarily mean it's going to be freed. It just decrements the object's retain count. It's not until the retain count reaches 0 the object gets freed (and even then, the object might be in an autorelease pool and still not be freed quite then).

So, you might release your object but you could still be pointing to it. And then it could get autoreleased. And then you send it a message — but maybe the object is garbage now. That's bad.

Setting your pointer to nil after releasing it means you can't send a message to a garbaged object. You're done with that object, and you can say whatever you want to nil, no harm done.

jbrennan
A: 

In addition to the other replies it is common across many languages to set released objects to nil, especially when the objects aren't completely local (perhaps members of another object). This allows you to easily check and see if an object has been previously released so you can create it again if needed.

Donnie
+1  A: 
danyowdee