Retain count and dealloc in iPhone
I want to ask about the iPhone application and objective C question. In the implementation program, there are function called 'dealloc'开发者_开发知识库, does this function only be called one time by the application?
For example, if I alloc a object and retain it 2 times, the retains count is 2 and I never use 'release' in the program, unless in the dealloc. Will the object be removed from the memory, or the objective will be removed from the memory. Thank you.
In the implementation program, there are function called 'dealloc', does this function only be called one time by the application?
Yes. -dealloc
destroys the object. Trying to send any message to it again, including -dealloc
is an error.
if I alloc a object and retain it 2 times, the retains count is 2
Careful. The retain count is at least 3. Other things than your code might retain the object. It's better not to worry to much about retain counts and only think in terms of ownership.
Each alloc, new, copy or retain is an claim of ownership. The object's dealloc method will only be called when all claims of ownership have been relinquished. A claim of ownership is relinquished by sending -release
. So if you never release an object except in its own dealloc, you'll never release it.
dealloc
is called once by the system when the object is destroyed (when its reference count reaches 0). If you have member variables in your class that you alloc
in your init
function, you must release
them in your dealloc
function.
If you give someone a pointer to one of those member objects and they retain
it, the member could survive the release
in your dealloc
, but by sending a retain
message they are taking responsibility for sending a release
message later, ensuring its eventual destruction.
精彩评论