Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท Memory Management and ARC

Retain Cycles and Autorelease Pools

Find and fix retain cycles with weak references, understand autorelease and @autoreleasepool blocks, spot leaks in loops, and learn the tools that catch memory problems in Objective-C code.

Reference counting has one famous blind spot: cycles. If object A owns object B and B owns A, neither count can reach zero, even after the rest of the program has forgotten them both. ARC does not detect this. It is the most common memory leak in modern Objective-C, and fixing it is a design decision, not a compiler setting.

The second half of this lesson covers the other piece of the memory story, the autorelease pool, which explains why some objects live a little longer than you expect and how to keep loops from ballooning memory.

What a cycle looks like

OBJECTIVEC
@interface Parent : NSObject
@property (nonatomic, strong) Child *child;
@end

@interface Child : NSObject
@property (nonatomic, strong) Parent *parent;   // BUG: should be weak
@end

Parent *p = [[Parent alloc] init];
Child  *c = [[Child alloc] init];
p.child  = c;     // c count = 2 (variable + parent)
c.parent = p;     // p count = 2 (variable + child)
p = nil;          // p count = 1 (still held by c)
c = nil;          // c count = 1 (still held by p): both leak

Each object is kept alive by the other. Nothing outside can reach them, and they will never be freed. The rule that prevents this: ownership must form a tree, with back-pointers weak. Parents own children strongly, children point back with weak.

flowchart LR
  P["Parent"] -- "strong" --> C["Child"]
  C -. "weak" .-> P

A strong arrow down and a weak arrow back means the cycle is broken.

See the leak with counts

The C model below gives each object a count and links two of them in a cycle. After both "variables" are dropped, the counts stay at 1 and nothing is freed. Then the same program with a non-owning back pointer frees both.

C Stand-in: a cycle that never frees

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.

In the strong scenario nothing prints "freed", because every count stays above zero. In the weak scenario, releasing the last outside references lets the parent die, which releases the child.

Cycles through blocks

Blocks capture the objects they use, and a captured self is a strong reference. If self stores the block, you have a cycle: self owns the block and the block owns self.

OBJECTIVEC
self.onFinish = ^{
    [self reload];            // captures self strongly: cycle!
};

// Fix: capture a weak reference, then promote it for the block's duration
__weak typeof(self) weakSelf = self;
self.onFinish = ^{
    typeof(self) strongSelf = weakSelf;   // "weak-strong dance"
    if (!strongSelf) return;
    [strongSelf reload];
};

Blocks and memory comes back to this. Other classic cycles: a delegate declared strong, an NSTimer retaining its target, and notification observers that are never removed.

Autorelease and @autoreleasepool

Sometimes a method has to return an object it created, but it cannot release it before returning, and the caller should not have to. The answer is autorelease: "release this later, when the current pool drains". The object stays valid for the rest of the calling code, then is released automatically.

Most convenience constructors ([NSString stringWithFormat:...], [NSArray array]) return autoreleased objects, which is why you do not own them.

A pool is created by @autoreleasepool { ... }. The main run loop wraps every event in one, so autoreleased objects normally vanish after each event. In a long loop that creates many temporary objects, you can drain more often:

OBJECTIVEC
for (int i = 0; i < 1000000; i++) {
    @autoreleasepool {
        NSString *s = [NSString stringWithFormat:@"item %d", i];
        [self process:s];
    }   // temporaries from this iteration are released here
}

Without the inner pool, a million strings would pile up until the outer pool drained, and memory use would spike. ARC reduces how many autoreleases occur, but the idiom is still important for batch work and in command-line programs, where you wrap the whole of main in a pool.

A pool as a stack

Conceptually a pool is a list: autorelease appends an object, and draining the pool releases each item once, in order. The stand-in below shows memory piling up without a pool and being freed per iteration with one.

C Stand-in: draining an autorelease pool

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.

Finding leaks in real projects

  • Instruments (Leaks and Allocations) shows leaked objects and growth over time.
  • The Memory Graph Debugger in Xcode displays object graphs, and cycles appear as loops.
  • -dealloc logging: add NSLog(@"%@ dealloc", self) while debugging. If it never prints when you expect it to, something still owns the object.
  • Compiler warnings such as "capturing 'self' strongly in this block is likely to lead to a retain cycle" are worth fixing, not silencing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do two objects that own each other leak?

    Neither count can reach zero while the other still holds it, and nothing outside can break the loop.
  2. 2. How do you fix a parent and child cycle?

    Ownership should form a tree; back-references are weak.
  3. 3. What does @autoreleasepool { } do at its closing brace?

    Draining the pool sends release to each autoreleased object.
  4. 4. Why wrap the body of a huge loop in its own pool?

    An inner pool bounds peak memory by releasing each iteration's temporaries.

Summary

  • Cycles leak under ARC; break them with a weak back-reference.
  • Blocks capture self strongly; use the weak-strong pattern when self stores the block.
  • autorelease defers a release to the end of the nearest pool; use @autoreleasepool in heavy loops.
  • Instruments, the Memory Graph Debugger and dealloc logs are the tools for finding leaks.

Next: Protocols