- Retaining and Releasing
- Assigning to Instance Variables
- Automatic Reference Counting
- Returning Objects via Pointer Arguments
- Avoiding Retain Cycles
- Migrating to ARC
- Autorelease Pools
- Using Autoreleased Constructors
- Autoreleasing Objects in Accessors
- Supporting Automatic Garbage Collection
- Interoperating with C
- Understanding Object Destruction
- Using Weak References
- Allocating Scanned Memory
Understanding Object Destruction
From: dealloc.m
There are three methods that are invoked during the destruction of an object, depending on the mode. One will run every time, but cannot be written by you. The -.cxx_destruct method is always called by the Objective-C runtime and handles the destruction of any fields that the compiler is responsible for cleaning up. This includes C++ objects in Objective-C++ mode and Objective-C object pointers in ARC mode.
The other two methods are -finalize and -dealloc. In garbage collected mode, you do not need to do anything to relinquish references to Objective-C objects, but you do still need to clean up any resources that are not managed by the garbage collector. This includes closing file handles, freeing memory allocated with malloc(), and so on. If your class has instance variables that need this kind of manual cleanup, then you should declare a -finalize method.
If you are not using garbage collection, then you should do cleanup in a -dealloc method. The contents of this method depend on whether or not you are using ARC. Traditionally, -dealloc methods were full of -release message sends to every instance variable that the class declared. With ARC, this is not required. ARC will relinquish any owning references to objects in -.cxx_destruct, so you only need to clean up non-object instance variables in -dealloc.
In both GC and manual retain/release mode, you should forward the message to the superclass, calling [ super dealloc] or [ super finalize] as appropriate. In ARC mode, explicitly calling -dealloc is not permitted. Instead, ARC will insert a [ super dealloc] call at the end of your -dealloc method in any non-root class.
Note that the example at the start of this section is overly complicated. In real code, you are unlikely to need to support both ARC and manual retain/release modes. Both can interoperate in the same program. The only reason to support non-ARC mode is if you wish to support legacy compilers.