tags:

views:

45

answers:

2

Hi, everyone,

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.

+1  A: 

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.

jasongetsdown
thank you for your reply. If I forget to set the release, will some problems about the program or the object will remain in the memory? Thank you.
Questions
The object will remain in memory, which is a problem.
jasongetsdown
+1  A: 

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.

JeremyP
If you alloc an object and retain it twice the reference count is at least **3**. It starts at 1 and get incremented twice.
jasongetsdown
@jasongetsdown: Good spot. Thanks. I've amended my post.
JeremyP