Why set object to nil after sending release message in Obj-C
I see a lot开发者_如何学Go 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?
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.
Two things
- As jbrennan noted, nullifying the object-pointer will stop your program from crashing on the use of a previously
dealloc
ated object.
I think this is a bad thing though, as you are probably obfuscating a bug or conceptual weakness in the code this way.
If—on the other hand—the object you've just released goes out of scope or will otherwise definitely not be used again—this assignment will be stripped by the compiler during optimization, anyway. - In a garbage-collected environment, sending
release
to an object doesn't have any effect.
Depending on what you are doing and where you do it, setting the object-pointer to nil may make the difference whether the GC will reap the object or not.
So without the assignment the object may live on and would not only block resources, but as it's fully alive and valid, may produce spurious side-effects.
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.
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.
精彩评论