This document summarizes the rules for memory management in Objective-C.
This is the fundamental rule:
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.
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.)
A received object is normally guaranteed to remain valid within the method it was received in (exceptions include multithreaded applications and some Distributed Objects situations, although you must also take care if you modify the object from which you received the object). That method may also safely return the object to its invoker.
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 (see “Validity of Shared Objects”).
autorelease
just means “send a release
message later” (for some definition of later—see “Autorelease Pools”).
For a more complete discussion of memory management in Objective-C see “Object Ownership and Disposal.”
© 2009 Apple Inc. All Rights Reserved. (Last updated: 2009-05-06)