Why does this iOS view controller leak memory after popping?
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:
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.
- Trace the ARC reference counts on pop and explain both the leak and the crash.
- Fix the leak safely and compare
[weak self],[unowned self], non-escaping closures, andweak var delegate.
Show hints (3)
- "TRACE THE CYCLE"
ChatViewControllerstrongly ownsclient,clientstrongly ownsonMessage, and the escaping closure strongly capturesself. Popping only drops the navigation stack's reference. - "WHY UNOWNED CRASHES"
[unowned self]breaks the strong cycle, sodeinitruns on pop. If the closure still fires200 mslater, dereferencing a deallocated unowned reference traps immediately. - "CAPTURE WEAK SELF"
Use
[weak self]withguard let self else { return }. For delegate objects, constrain the protocol toAnyObjectand storeweak 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 pattern | increments strong count | if self frees first | when to use |
|---|---|---|---|
strong self | yes (+1) | keeps self alive (leaks cycles) | short work not owned back by self |
[weak self] | no (0) | zeroes safely to nil | stored or async escaping closures |
[unowned self] | no (0) | fatal runtime trap | guaranteed equal or longer lifetime |
| non-escaping closure | temporary only | cannot outlive call | synchronous 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.
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 afterdeinittriggers a fatal crash. - Writing
[weak self]inside non-escaping synchronous closures likeitems.map { ... }. Non-escaping closures finish before returning and cannot create retain cycles. - Declaring a delegate property without
weak(or forgetting: AnyObjecton the delegate protocol), creating a classic two-objectVC <-> Clientretain cycle. - Storing
Timer.scheduledTimerorNotificationCenter.addObserver(forName:using:)closures capturingselfstrongly without invalidating or removing the observer.
Follow-up questions
- "Does a Swift Task { self.load() } or URLSession completion handler always require [weak self]?" If
selfdoes not strongly store thatTaskor closure, there is no permanent cycle, only temporary retention until the request finishes. Still, using[weak self](or cancelling a storedTaskindeinit) lets the view controller free its12 MBright 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 forChatViewController; 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 outliveself. A classic example is a synchronous lazy property owned solely byselfand 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 →