skip to content

In Objective-C, an upload controller's copied progress block updates _sentBytes and the controller never deallocates; why, and how do __weak and __strong fix it?

level: seniorimportance: must knowfreq 65%

answer

  1. who owns the block, whom the block owns
  2. an ivar is reached through self
  3. -Warc-retain-cycles misses the ivar form
  4. -Wimplicit-retain-self flags it
  5. weakSelf outside, strongSelf inside, nil check

basics

~20 s

Inside a block, _sentBytes means self->_sentBytes, so the block captures self strongly while self owns the block through its copy property: a cycle. Capture a __weak self, promote it to a __strong local inside the block, and return when it is nil.

solid answer

~40 s

Blocks keep strong references to the objects they capture, and clang's blocks specification says instance variables used in a block are reached through `self`, so `self` is captured. The controller owns the block through its `copy` property, and the block owns the controller, so neither ever deallocates. Clang warns "capturing 'self' strongly in this block is likely to lead to a retain cycle" for `[self updateStatus]`, but not for a bare ivar; the off-by-default `-Wimplicit-retain-self` is what flags that. The fix is the weak-strong dance: declare `__weak typeof(self) weakSelf = self;` outside, then `__strong typeof(weakSelf) strongSelf = weakSelf;` inside, return if it is `nil`, and use `strongSelf->_sentBytes`. ARC rejects `weakSelf->_sentBytes` outright. `__block` does not help under ARC, because a `__block` object variable is retained there.

code

objective-c · 31 lines
objective-c
#import <Foundation/Foundation.h>

@interface PPUploadController : NSObject {
    NSUInteger _sentBytes;
}
@property (nonatomic, copy) void (^progressHandler)(NSUInteger bytes);
@property (nonatomic, copy) NSString *status;
@end

@implementation PPUploadController
- (void)configureLeaky {
    // _sentBytes means self->_sentBytes: the block retains self,
    // and self retains the block through the copy property.
    self.progressHandler = ^(NSUInteger bytes) {
        _sentBytes += bytes;
    };
}

- (void)configure {
    __weak typeof(self) weakSelf = self;
    self.progressHandler = ^(NSUInteger bytes) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf == nil) {
            return;  // the controller is gone; drop the update
        }
        strongSelf->_sentBytes += bytes;
        strongSelf.status = [NSString stringWithFormat:@"%lu bytes sent",
                             (unsigned long)strongSelf->_sentBytes];
    };
}
@end

go deeper

for a junior

Recall that blocks retain captured objects and that a block stored on self which uses self forms a cycle.

for a middle

Explain the weak-strong dance step by step and why the strong local does not recreate the cycle.

for a senior

Find the hidden cases: bare ivars, cycles through owned objects, __block code carried over from manual counting. Know which clang warnings catch which pattern.

for a principal

Decide team policy: enable -Wimplicit-retain-self, treat retain-cycle warnings as errors, and agree when weak capture is a lifetime choice rather than a reflex.

## The ownership loop A **block** is an Objective-C object that captures the variables it uses. Apple's blocks guide states that blocks keep **strong references to any captured objects, including `self`**. A block stored in a property is copied to the heap and owned by that property. Put the two together in one class: 1. The upload controller owns `progressHandler` through a `copy` property. 2. The block uses the controller, so it owns the controller. 3. Neither reference count can reach zero, so the controller and its block leak, and the controller's `dealloc` never runs. In a photo-printing app this shows up as an upload screen that is dismissed but keeps receiving progress, or as memory that grows each time an order is opened. ## Why an ivar captures self The bug is hardest to see when the block never writes `self`: ```objective-c self.progressHandler = ^(NSUInteger bytes) { _sentBytes += bytes; }; ``` Clang's blocks specification explains it: instance variables referenced in a block inside a method are implicitly qualified as references from `self`, so `self` is captured. `_sentBytes` is really `self->_sentBytes`, and the block retains the controller just as `[self updateStatus]` would. ## What the compiler tells you | Code inside a block stored on `self` | Default diagnostics | With `-Wimplicit-retain-self` | |---|---|---| | `[self updateStatus];` | `-Warc-retain-cycles`: capturing 'self' strongly is likely to lead to a retain cycle | same | | `_sentBytes += bytes;` | nothing | "block implicitly retains 'self'; explicitly mention 'self'" | | `weakSelf->_sentBytes += bytes;` | error: dereferencing a `__weak` pointer is not allowed | same | The retain-cycle warning catches simple, direct patterns; Apple's guide notes that cycles through several objects are harder to diagnose. Turning on `-Wimplicit-retain-self` makes the ivar case visible. ## The weak-strong dance 1. **Outside the block**, take a weak reference: `__weak typeof(self) weakSelf = self;`. The block captures `weakSelf`, which does not retain the controller, so the loop is broken. 2. **First line inside**, promote it: `__strong typeof(weakSelf) strongSelf = weakSelf;`. This local keeps the controller alive for the rest of this run of the block only; it is released when the block returns, so it does not recreate the cycle. 3. **Check for nil** and return early. If the controller has already gone away, there is nothing to update. 4. **Use `strongSelf`** for every message and every ivar: `strongSelf->_sentBytes`. Why not just use `weakSelf` everywhere? A single message to `weakSelf` is fine, because a message to `nil` does nothing. But across several statements the controller could be deallocated in between, leaving half an update applied, and `->` on a `nil` pointer is a memory access that crashes. ARC forbids dereferencing a `__weak` pointer for exactly that reason. ## __block under ARC and under manual counting Older code broke cycles with `__block`. Apple's ARC transition notes explain why that no longer works: under manual reference counting, `__block id x;` did **not** retain `x`; under ARC, a `__block` object variable is retained like any other strong variable. A converted file that still uses `__block PPUploadController *blockSelf = self;` therefore leaks. The notes suggest `__weak` instead, or setting the `__block` variable to `nil` once the block is done with it. `__block` remains the tool for its real job: letting a block modify a captured local, such as a running byte total. ## Other ways out, and when no fix is needed - **One-shot handlers**: if the block is cleared after it runs, for example `self.progressHandler = nil;` when the upload finishes, the cycle is temporary. That only works if the finishing path always runs. - **Pass the object in**: a block that receives the controller as a parameter does not need to capture it. - **No ownership, no cycle**: a completion block handed to another object, which calls it and then releases it, keeps `self` alive only until then. Weakening `self` there is a choice about lifetime, not a leak fix. ## Confirming the fix Put a log line in the controller's `dealloc`, open and close the upload screen, and watch for it. If it never prints, something still owns the controller: the block, a timer, an observer registration or another object holding it strongly. Fixing one capture and still seeing no `dealloc` usually means a second path into the same cycle. In review, look for blocks stored on `self` or on an object `self` owns, and treat bare ivars inside them as `self`.

  • Why not call `[weakSelf updateStatus]` without promoting it to a strong local?
    For one message that is fine: if the controller is gone, the message goes to `nil` and does nothing. With several statements, the controller can be deallocated between them, so part of the work runs and part does not, and `weakSelf->_sentBytes` will not compile under ARC. The strong local fixes the lifetime for one run of the block.
  • Does every block that mentions self create a retain cycle?
    No. A cycle needs `self`, or something `self` owns, to hold the block. A completion block passed to another object that calls it once and then releases it keeps `self` alive only until it runs. Using a weak reference there changes behaviour: work after the screen closes is skipped. That is sometimes desired, but it is a separate decision.
  • What did __block change about capturing self when a codebase moved from manual counting to ARC?
    Under manual reference counting, a `__block` object variable was not retained, so `__block id blockSelf = self;` broke cycles. Under ARC it is retained by default, so the same line now leaks. Replace it with `__weak`, or set the `__block` variable to `nil` when the block finishes.

  • Using _sentBytes instead of self.sentBytes avoids capturing self.
  • The compiler always warns when a stored block captures self.
  • __block self breaks the cycle under ARC just as it did under manual counting.
  • Every block that mentions self needs weakSelf, even one-shot completions passed elsewhere.
  • weakSelf->_sentBytes is fine once weakSelf has been checked for nil.
  • The strong local inside the block recreates the retain cycle.