About dealloc/release: is it always OK to do x = nil; [x release]; - or can it cause problems?
since every assignment to a variable with a different object increases its retain count and in the dealloc its not always clear how often a variable got assigned a simple [maVar release] might NOT BE SUFFICIENT. So using ALWAYS myVar = nil
sets the retain count to zero, and a subsequent [myVar release]
will开发者_Go百科 never cause a problem again. (is it actually still required ?)
The only situation when not to do it this way is if myVar is passed OUT then I must not do this, since the value gets destroyed by myVar = nil
;
Is my thinking correct? Or could this way of avoiding leaks cause any other problems?
Your thinking is incorrect in quite a lot of ways. These are probably just scratching the surface:
- Assignment to a variable does not increase its retain count. (There are some subtleties to do with properties, but frankly that's way beyond the level we're at here.)
dealloc
is called when the retain count reaches 0.- Setting
myVar = nil
does not affect the retain count. myVar = nil
destroys only the local pointer value, it does not destroy an object that has been passed out.- It is safe to call
[myVar release]
whenmyVar
isnil
, but it isn't useful -- it does nothing. - Worrying about retain counts is always a mistake. Worry about what you own.
It is clear that your grasp of C pointers and Objective-C memory management is a bit lacking. I'd suggest doing some remedial C work before several thorough re-reads of the Memory Management docs.
Please read Apple's documentation on Memory Management.
Assigning a pointer to an object will not increment the retain
count, only calling retain
does that. Functions with Copy or Init in the name should return an object with a retain count of 1, other functions should return autoreleased objects that will be dealloc'd when the main loop finishes.
Setting an object to nil
doesn't modify the retain count, but it will cause that memory to leak. Calling release
on the pointer at that point essentially does nothing. You need to be responsible about using retain
, release
, autorelease
, and how you name your functions if you want to effectively manage your memory usage.
精彩评论