This article summarizes the rules for memory management in Objective-C.
This is the fundamental rule:
You only release or autorelease objects you own.
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 use release
or autorelease
to relinquish ownership of an object. autorelease
just means “send a release
message in the future” (to understand when this will be, see “Autorelease Pools”).
The following rules derive from the fundamental rule, or cope with edge cases:
As a corollary of the fundamental rule, if you need to store a received object as a property in an instance variable, you must retain or copy it. (This is not true for weak references, described at “Weak References to Objects,” but these are typically rare.) Generally you devolve responsibility for doing this to accessor methods (see “Accessor Methods”).
A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. Exceptions include multithreaded applications and some Distributed Objects situations, although you must also take care if you modify an object from which you received another object (see “Validity of Shared Objects”). Use retain
in combination with release
or autorelease
when needed to prevent an object from being invalidated as a normal side-effect of a message.
The reasoning behind these rules is discussed in “Object Ownership and Disposal.”
Important: There are similar memory management rules for Core Foundation objects (see Memory Management Programming Guide for Core Foundation). The naming conventions for Cocoa and Core Foundation, however, are different. In particular, Core Foundation’s “create rule in Memory Management Programming Guide for Core Foundation” does not apply to methods that return Objective-C objects. For example, in the following code fragment, you are not responsible for relinquishing ownership of myInstance
:
MyClass *myInstance = [MyClass createInstance]; |
Last updated: 2010-06-24