Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Memory Management and ARC

Reference Counting and Object Ownership

Understand how Objective-C objects live and die - retain counts, ownership rules, retain, release and autorelease - the model that ARC automates, with a runnable C stand-in.

Every Objective-C object lives on the heap, and something has to decide when its memory can be reused. Objective-C does not use a tracing garbage collector. It uses reference counting: each object keeps a number that says how many owners want it to stay alive. When the number reaches zero, the object is destroyed.

Today the compiler inserts the counting calls for you (that is ARC), but the model underneath is unchanged. If you do not understand it, you will not understand retain cycles, weak, copy, autorelease pools or the crashes that come with them. This lesson teaches the model, first in words, then with a small C program that behaves the same way.

Objective-C does not run on this site, so the Objective-C snippets are read-only. The runnable examples are plain C programs that reproduce the mechanism. They are labelled as stand-ins.

The ownership rules

Cocoa's memory management is built on a handful of rules about ownership:

  1. You own any object you create with a method whose name starts with alloc, new, copy or mutableCopy.
  2. You can take ownership of an object you received by sending it retain.
  3. When you no longer need an object you own, you must give up ownership with release (or autorelease).
  4. You must not release an object you do not own.

The count is stored in the object itself. alloc creates the object with a count of 1. retain adds one. release subtracts one, and at zero the runtime calls dealloc and frees the memory.

OBJECTIVEC
// Manual reference counting (pre-ARC style, shown for understanding)
NSMutableArray *list = [[NSMutableArray alloc] init]; // count = 1, you own it
[list retain];                                         // count = 2
[list release];                                        // count = 1
[list release];                                        // count = 0 -> dealloc

Names matter because they are the contract. [NSString stringWithFormat:...] does not start with alloc, new or copy, so you do not own the result: someone else (an autorelease pool, see autorelease pools) will release it. If you need it to outlive the current scope, you must retain it.

A model you can run

The program below has a tiny Object with a count and a name. obj_alloc starts at 1, obj_retain increments, obj_release decrements and frees at zero, printing when the "dealloc" happens. It is not Objective-C, but the behavior is identical to the example above.

C Stand-in: a reference counter in C

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice the symmetry: every alloc and retain must be matched by exactly one release. Miss one and you leak. Add one too many and you free an object that someone still uses.

Who owns what: collections and properties

Collections own their elements. When you add an object to an NSMutableArray, the array retains it. When you remove it or the array dies, the array releases it. That is why this is safe:

OBJECTIVEC
NSMutableArray *names = [[NSMutableArray alloc] init];
NSString *title = [[NSString alloc] initWithFormat:@"Report %d", 7]; // count 1
[names addObject:title];   // array retains: count 2
[title release];           // you give up your claim: count 1, the array keeps it alive

The same idea drives properties. A strong (or in manual days, retain) property owns its value: assigning a new value retains it and releases the old one. A weak property does not own anything, and a copy property owns a private copy. Strong and weak references covers these in depth.

Sharing an object between two owners

A common scenario: a view controller and a model both need the same object. With reference counting, they simply both own it. Neither needs to know about the other. The object dies when the last owner lets go.

C Stand-in: two owners share one object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The setter retains the new value before releasing the old one. If you did it the other way around and the two were the same object, you would free it before you retained it. Hand-written setters in the MRC era always had this shape, and it is exactly what ARC generates for you.

Common mistakes

  • Over-release: releasing an object twice sends a message to freed memory, a classic crash (EXC_BAD_ACCESS, "message sent to deallocated instance").
  • Leak: forgetting a release after alloc, so the count never reaches zero.
  • Retaining what you do not need: storing a pointer without retaining it, then using it after its real owner died (a dangling pointer).
  • Forgetting [super dealloc] in a manual-counting dealloc, which leaks the superclass's state.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the reference count of an object right after [[Foo alloc] init]?

    alloc returns an object you own, and a new object starts with a count of 1.
  2. 2. Which method name tells you that you own the returned object?

    Methods beginning with alloc, new, copy or mutableCopy return an object you own and must balance.
  3. 3. Why does a setter retain the new value before releasing the old one?

    If both are the same object and its only owner is the property, releasing first would free it before it is retained.
  4. 4. What happens when the retain count reaches zero?

    At zero nobody owns the object, so it is deallocated.

Summary

  • Objects are reference counted; each owner keeps the object alive.
  • You own what you alloc, new, copy or mutableCopy, or what you retain; you balance each with release.
  • Collections and strong properties own their contents.
  • Leaks, over-releases and dangling pointers are the bugs ARC was invented to remove.

Next: Automatic Reference Counting