download

Why does this iOS view controller leak memory after popping?

Mobile~8 minReviewed 3 Dec 2026Free · No sign-in

Question

Each time you open and close ChatViewController (12 MB of cached attachments), memory grows by 12 MB and deinit never runs. After 10 visits, 120 MB stays leaked until iOS kills the app:

"SWIFT"
final class StreamClient {
    var onMessage: ((String) -> Void)?
}

final class ChatViewController: UIViewController {
    private let client = StreamClient()
    override func viewDidLoad() {
        super.viewDidLoad()
        client.onMessage = { text in
            self.appendMessage(text)
        }
    }
    deinit { print("deinit ChatViewController") }
}

A teammate changes the closure to [unowned self]. Now deinit runs, but a message arriving 200 ms after popping crashes with a fatal runtime trap.

  1. Trace the ARC reference counts on pop and explain both the leak and the crash.
  2. Fix the leak safely and compare [weak self], [unowned self], non-escaping closures, and weak var delegate.
Show hints (3)
  1. "TRACE THE CYCLE"

    ChatViewController strongly owns client, client strongly owns onMessage, and the escaping closure strongly captures self. Popping only drops the navigation stack's reference.

  2. "WHY UNOWNED CRASHES"

    [unowned self] breaks the strong cycle, so deinit runs on pop. If the closure still fires 200 ms later, dereferencing a deallocated unowned reference traps immediately.

  3. "CAPTURE WEAK SELF"

    Use [weak self] with guard let self else { return }. For delegate objects, constrain the protocol to AnyObject and store weak var delegate.

Show checked explanation

The controller, StreamClient, and escaping onMessage closure form a strong reference cycle (VC -> client -> closure -> VC). Popping drops the controller's strong count from 2 to 1, so deinit never runs and 10 visits leak 120 MB. Use [weak self] with guard let self else { return }; [unowned self] crashes with a fatal trap if an async callback fires after deinit.

ARC strong/weak/unowned reference-count transitions, 10-navigation 120 MB leak growth, and post-deinit unowned trap behavior were simulated on CPython 3.12.10 (no Swift toolchain or Xcode installed locally); Swift ARC and closure rules checked against official Swift and Apple documentation. Checked by an editor other than the author.

Walkthrough

Swift's Automatic Reference Counting (ARC) frees a class instance only when its strong reference count reaches 0. While ChatViewController is on screen, two strong references keep it alive: the navigation stack (+1) and the escaping onMessage closure stored on client (+1), giving a strong count of 2.

When the user taps Back, the navigation stack releases its reference and the strong count drops from 2 to 1. Because VC -> client -> closure -> VC still holds each object at count 1, ARC can never free the cycle. Ten visits leak 10 * 12 MB = 120 MB.

capture or patternincrements strong countif self frees firstwhen to use
strong selfyes (+1)keeps self alive (leaks cycles)short work not owned back by self
[weak self]no (0)zeroes safely to nilstored or async escaping closures
[unowned self]no (0)fatal runtime trapguaranteed equal or longer lifetime
non-escaping closuretemporary onlycannot outlive callsynchronous APIs (map, filter)

Switching to [unowned self] stopped the leak because the count dropped 1 -> 0 on pop. However, an async callback arriving 200 ms later through a shared transport still ran the closure and hit a deterministic Swift runtime trap.

"SWIFT"
protocol StreamDelegate: AnyObject {
    func didReceive(_ text: String)
}

final class ChatViewController: UIViewController {
    private let client = StreamClient()

    override func viewDidLoad() {
        super.viewDidLoad()
        client.onMessage = { [weak self] text in
            guard let self else { return }
            self.appendMessage(text)
        }
    }
    deinit { print("deinit ChatViewController") }
}

With [weak self], popping drops the strong count from 1 to 0, and deinit runs right away (0 MB leaked across 10 visits). client then deallocates and cleans up its socket in StreamClient.deinit, while any late callback sees nil and exits safely. Keeping non-Sendable socket teardown out of ChatViewController.deinit also stays valid under Swift 6 (UIViewController is @MainActor, while deinit is nonisolated). If you use a delegate instead of a closure, mark the protocol : AnyObject and declare weak var delegate: (any StreamDelegate)? so the child never retains its parent.

Common mistakes

  • Assuming [unowned self] is a faster drop-in replacement for [weak self] in async callbacks. Any callback firing after deinit triggers a fatal crash.
  • Writing [weak self] inside non-escaping synchronous closures like items.map { ... }. Non-escaping closures finish before returning and cannot create retain cycles.
  • Declaring a delegate property without weak (or forgetting : AnyObject on the delegate protocol), creating a classic two-object VC <-> Client retain cycle.
  • Storing Timer.scheduledTimer or NotificationCenter.addObserver(forName:using:) closures capturing self strongly without invalidating or removing the observer.

Follow-up questions

  • "Does a Swift Task { self.load() } or URLSession completion handler always require [weak self]?" If self does not strongly store that Task or closure, there is no permanent cycle, only temporary retention until the request finishes. Still, using [weak self] (or cancelling a stored Task in deinit) lets the view controller free its 12 MB right away when popped instead of waiting for a slow network timeout.
  • "How do you track down a retain cycle like this in Xcode?" Navigate into and out of ChatViewController, then open Xcode's Debug Memory Graph (or the Leaks instrument). Filter for ChatViewController; surviving instances appear in the graph with the exact strong reference chain (ChatViewController -> StreamClient -> closure -> ChatViewController).
  • "When is [unowned self] actually safe to use?" Use [unowned self] only when the closure can never outlive self. A classic example is a synchronous lazy property owned solely by self and never passed to another object.

What a strong answer covers

Traces the strong count dropping from 2 to 1 on pop (VC -> client -> closure -> VC), fixes with [weak self] plus guard let self, explains why [unowned self] traps on late callbacks, and contrasts non-escaping closures and weak var delegate: (any StreamDelegate)?.

Open in interactive practice deck →

Original OfferVibe question. Swift Automatic Reference Counting · Swift Closures · Gathering information about memory use.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.