Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why set object to nil after sending release message in Obj-C

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?

like image 809
cpjolicoeur Avatar asked Jun 18 '10 17:06

cpjolicoeur


1 Answers

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.

like image 116
jbrennan Avatar answered Sep 24 '22 21:09

jbrennan