Objective-C Block Retain Cycles
Overview
Block retain cycles are the #1 cause of Objective-C memory leaks. When a block captures self and is stored on that same object (directly or indirectly through an operation/request), you create a circular reference: self β block β self. Core principle 90% of block memory leaks stem from missing or incorrectly applied weak-strong patterns, not genuine Apple framework bugs.
Red Flags β Suspect Block Retain Cycle
If you see ANY of these, suspect a block retain cycle, not something else:
- Memory grows steadily over time during normal app use
- UIViewController instances not deallocating (verified in Instruments)
- Crash: "Sending message to deallocated instance" from network/async callback
- Network requests or animations prevent view controller from closing
- Weak reference becomes nil unexpectedly in a block
- NSLog, NSAssert, or string formatting hiding self references
- Completion handler fires after the view controller "should be gone"
- β FORBIDDEN Rationalizing as "It's probably normal memory usage"
- Memory leaks are never "normal"
- Apps should return to baseline memory after user dismisses a screen
- Do not rationalize this as "good enough" or "monitor it later"
Critical distinction Block retain cycles accumulate silently. A single cycle might be 100KB, but after 50 screens viewed, you have 5MB of dead memory. MANDATORY: Test on real device (oldest supported model) after fixes, not just simulator.
Mandatory First Steps
ALWAYS run these FIRST (before changing code):
What this tells you
- Memory stays high β Leak confirmed, not false alarm
- ViewController retained by operation β Block is the culprit
- Block references self β Pattern: weak-strong needed
- Hidden self in NSLog/NSAssert β Need to check ALL macro calls
- No self references found β Maybe not a block cycle, investigate elsewhere
MANDATORY INTERPRETATION
Before changing ANY code, you must confirm ONE of these:
- If memory doesn't return to baseline AND ViewController still allocated β Block retain cycle exists
- If memory returns to baseline β Not a retain cycle, investigate other causes
- If cycle exists but you can't find self references β Check for hidden references (macros, indirect property access)
- If you find the cycle but don't understand the chain β Trace backward through retained objects in Memory Graph
If diagnostics are contradictory or unclear
- STOP. Do NOT proceed to patterns yet
- Add more diagnostics: Print the object graph, list retained objects
- Ask: "If memory is low, why is the ViewController still allocated?"
- Run Instruments > Leaks instrument if memory graph is confusing
Decision Tree
Block memory leak suspected?
ββ Memory stays high after dismiss?
β ββ YES
β β ββ ViewController still allocated in Memory Graph?
β β β ββ YES β Proceed to patterns
β β β ββ NO β Not a block cycle, check other leaks
β β ββ NO β Not a leak, normal memory usage
β β
β ββ Crash: "Sending message to deallocated instance"?
β ββ Happens in block/callback?
β β ββ YES β Block captured weakSelf but it became nil
β β β ββ Apply Pattern 4 (Guard condition is wrong or missing)
β β ββ NO β Different crash, not block-related
β ββ Crash is timing-dependent (only on device)?
β ββ YES β Weak reference timing issue, apply Pattern 2
β
ββ Block assigned to self or self.property?
β ββ YES β Apply Pattern 1 (weak-strong mandatory)
β ββ Assigned through network operation/timer/animation?
β β ββ YES β Apply Pattern 1 (operation retains block indirectly)
β ββ Block called immediately (inline execution)?
β ββ YES β Optional to use weak-strong (no cycle possible)
β β ββ But recommend for consistency with other blocks
β ββ NO β Block stored or passed to async method β Use Pattern 1
β
ββ Multiple nested blocks?
β ββ YES β Apply Pattern 3 (must guard ALL nested blocks)
β
ββ Block contains NSAssert, NSLog, or string format with self?
β ββ YES β Apply Pattern 2 (macro hides self reference)
β
ββ Implemented weak-strong pattern but still leaking?
ββ Check: Is weakSelf used EVERYWHERE?
ββ Check: No direct `self` references mixed in?
ββ Check: Nested blocks also guarded?
ββ Check: No __unsafe_unretained used?
Common Patterns
Pattern Selection Rules (MANDATORY)
Apply ONE pattern at a time, in this order
-
Always start with Pattern 1 (Weak-Strong Basics)
- If block assigned to self or self's properties β Pattern 1
- If block passed to operation/request that retains it β Pattern 1
- Only proceed to Pattern 2 if pattern still leaks
-
Then Pattern 2 (Hidden self in Macros)
- Only if memory still leaks after applying Pattern 1
- Check for NSAssert, NSLog, string formatting
- If found, apply Pattern 2
-
Then Pattern 3 (Nested Blocks)
- Only if block has nested callbacks
- Each nested block needs its own guard
- If found, apply Pattern 3
-
Then Pattern 4 (Guard Condition Edge Cases)
- Only if crash happens with weakSelf approach
- Check guard condition is correct
- Verify strongSelf used everywhere
FORBIDDEN
- β Applying multiple patterns at once
- β Skipping Pattern 1 because "I already know weak-strong"
- β Using __unsafe_unretained as workaround
- β Using strong self "just this once"
- β Rationalizing: "The block is too small for a leak"
Pattern 1: Weak-Strong Pattern (MANDATORY)
PRINCIPLE Any block that captures self must use weak-strong pattern if block is retained by self (directly or transitively).
β WRONG (Creates retain cycle)
[self.networkManager GET:@"url" success:^(id response) {
self.data = response;
[self updateUI];
} failure:^(NSError *error) {
[self handleError:error];
}];
β
CORRECT (Breaks the cycle)
__weak typeof(self) weakSelf = self;
[self.networkManager GET:@"url" success:^(id response) {
typeof(self) strongSelf = weakSelf;
if (strongSelf) {
strongSelf.data = response;
[strongSelf updateUI];
}
} failure:^(NSError *error) {
__weak typeof(self) weakSelf2 = self;
typeof(self) strongSelf = weakSelf2;
if (strongSelf) {
[strongSelf handleError:error];
}
}];
Why this works
__weak typeof(self) weakSelf = self; creates a weak reference outside the block
- Block captures weakSelf (weak reference), not self (strong reference)
- When block executes, convert to strongSelf (temporary strong ref)
- Check if strongSelf is nil (object was deallocated)
- Use strongSelf for the duration of the block
- strongSelf released when block exits β No cycle
Important details
- Declare weakSelf OUTSIDE the block, not inside
- Use
typeof(self) for type safety (works in both ARC and non-ARC)
- Guard condition MUST use
if (strongSelf), not just declare it
- Never use direct
self inside the block once weakSelf is declared
- Apply to EVERY block that captures self
- ANY block that captures
self must use weak-strong pattern
- This includes:
[self method], self.property, self->ivar
- Property access (
self.property = value) captures self just like method calls
- Blocks passed to frameworks:
- If framework documentation says 'block is called asynchronously' β Use weak-strong pattern (framework retains the block)
- If framework documentation says 'block is called immediately' β Still safe to use weak-strong (better practice)
- If unsure about framework behavior β Always use weak-strong (doesn't hurt)
Capturing variables (avoiding indirect self references)
__weak typeof(self) weakSelf = self;
[self.manager fetch:^(id response) {
typeof(self) strongSelf = weakSelf;
if (strongSelf) {
NSString *name = strongSelf.name;
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Name: %@", name);
});
}
}];
__weak typeof(self) weakSelf = self;
[self.manager fetch:^(id response) {
typeof(self) strongSelf = weakSelf;
if (strongSelf) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Name: %@", strongSelf.name);
});
}
}];
When nesting blocks, extract simple values first, then pass them to the inner block. This avoids creating an indirect capture of self through property access.
Time cost 30 seconds per block
Pattern 2: Hidden self in Macros