Cocoa Memory management conventions
Apple uses reference counting as the default memory management technique in its frameworks. Augmented with an autorelease pool that keeps track of the current stack frame and releases objects when the current stack frame exits, it is a reasonable balance between the performance of manual memory management and the comfort of garbage collection I am usually used to working on .NET projects.
However, reference counting establishes the need for ownership conventions that define who is responsible for releasing an object and under what circumstances I can assume a reference to be valid. Unfortunately, I have found these conventions hard to remember every time I created an object, because there are many of them (at least if you have just started Objective-C programming). Thought as a memo to myself, here follows the (hopefully complete) list of conventions:
- Objects retrieved via methods whose name begins with “alloc” or “new” or contains “copy” are retained. The caller is responsible for releasing the object.
- CoreFoundation Objects retrieved via C functions whose name contains “Create” or “Copy” are retained. The caller is responsible for releasing the object.
- In any other case, the caller is not responsible for releasing the object e.g. receiving a string from [NSString stringWithFormat:] returns an autoreleased object.
Loading Objects from NIB Files:
- Objects in the nib file are created with a retain count of 1 and then autoreleased.
- UIKit reestablishes connections between the objects using
setValue:forKey:, which uses the available setter method or retains the object by default if no setter method is available
- If there are any top-level objects you not stored in outlets, the caller must retain either the array returned by the
loadNibNamed:owner:options:method or the objects inside the array to prevent those objects from being released prematurely.
- The conventions governing receiving objects follow from the rules governing object creation
- A received object can be assumed valid throughout the scope of the caller
- If a caller wants to retain an object in another scope (e.g. storing it in a private field) he must call -retain and is responsible for releasing the object when done with it
This guide is probably not complete, however it contains the most important rules. For additional detail please see the resources below.
- Cocoa Memory Management Guide
- Core Foundation Memory Management Guide
- Memory Management of Nib Objects
- (Andrew M. Duncan) Objective-C Pocket Reference