简体   繁体   中英

iPhone SDK: Dealloc vs. Release?

I am wondering what the difference is between release and dealloc? After reading, the memory management rules (See below)., I am thinking most of the time I will be using release. However, I wanted to know what to do for properties.

@property(retain)....

I have been using dealloc but after reading this article I am not sure that is correct.

You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. You are responsible for relinquishing ownership of objects you own using release or autorelease. Any other time you receive an object, you must not release it.

You should never call dealloc on anything other than super .

The only time you will be calling dealloc is in the dealloc method of a custom inherited object, and it will be [super dealloc] .

When the retain count of an object goes down to zero, dealloc will automatically be called for you, so in order to manage memory properly, you need to call retain and release when appropriate.

If this isn't clear to you or you'd like details about how memory is managed in Cocoa, you should read the Memory Management Programing Guide .

You never call dealloc directly. It is invoked by the system when the retainCount of the object goes to 0. Every time you do a retain , the retainCount is incremented with 1. Every time you do a release , it gets decremented. This way, by balancing your retains and releases , you ensure than when the retainCount gets to 0, dealloc will be automatically called, and your object freed.

As Ben S noted, the only time and place you would call dealloc is in in the dealloc method of an inherited object.

When you use @property(retain) and then @synthesize to generate the property code, you do not need to do any manual memory management on the property. The other answers are correct in that you shouldn't be using dealloc except in your own override of a parent class dealloc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM