Home

retainrelease

Retainrelease, also known as the retain/release memory management pattern, is a memory management mechanism used in manual reference counting systems, most notably in Objective-C and the Cocoa frameworks before Automatic Reference Counting (ARC) was introduced. In this model, objects maintain a numeric reference count that represents ownership by parts of the program. Sending a retain message to an object increases its count, while sending a release message decreases it. When the count reaches zero, the object's dealloc method is invoked and its memory is reclaimed. To allow temporary ownership without immediate deallocation, objects can be sent an autorelease message, which places them in the current autorelease pool and releases them automatically when the pool is drained, typically at the end of the run loop iteration.

Ownership rules are central to the retainrelease pattern. You own objects you create with alloc/init, new, copy,

Common pitfalls include memory leaks from forgotten releases and retain cycles where two or more objects hold

In practice, retainrelease has largely been superseded by ARC, which automatically inserts retain and release calls.

or
mutableCopy,
and
you
are
responsible
for
releasing
or
autoreleasing
them
when
you
are
finished.
If
you
did
not
create
or
retain
an
object,
you
should
not
release
it.
If
you
want
to
transfer
ownership
to
another
part
of
the
program,
you
may
retain
the
object
to
keep
it
alive
and
later
release
it
when
it
is
no
longer
needed.
strong
references
to
each
other,
preventing
deallocation.
Tools
such
as
static
analyzers
and
careful
design
(for
example,
using
weak
references)
help
mitigate
these
issues,
especially
in
codebases
that
mix
manual
retainrelease
with
later
ARC.
Manual
retainrelease
code
remains
in
older
codebases
and
requires
disciplined
ownership
management.