A Swift autosave controller starts a repeating `Timer` whose block uses `self` and invalidates it in `deinit`; why does `deinit` never run, and how do you fix it?
answer
- who holds a scheduled timer
- timer, block, self
- deinit cannot break its own cycle
- weak capture plus invalidate()
basics
~20 sThe run loop retains the scheduled timer, the timer retains its block, and the block captures the controller strongly, so deinit, where invalidate() sits, never runs. Capture self weakly and invalidate the timer on stop or in deinit.
solid answer
~40 s`Timer.scheduledTimer(withTimeInterval:repeats:block:)` adds the timer to the current run loop, and the run loop keeps a strong reference to it until it is invalidated. The timer keeps its block, and a block that uses `self` strongly keeps the controller. So when the owning screen releases the controller, it is still reachable from the run loop: its `deinit` never runs, and the `invalidate()` call placed there is dead code. The fix has two halves: capture `[weak self]` in the block (with `guard let self else { return }`), so the timer no longer owns the controller, and invalidate the timer when the work should stop, from an explicit `stop()` or from `deinit`, which can now run. A weak capture alone stops the leak but leaves the timer firing with a `nil` `self` until something invalidates it.
code
swift · 23 linesimport Foundation
final class AutosaveController {
private var timer: Timer?
private(set) var saves = 0
func start() {
timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
self.saves += 1 // strong capture of self
}
}
deinit {
timer?.invalidate() // never reached while the timer runs
print("AutosaveController deinit")
}
}
var controller: AutosaveController? = AutosaveController()
controller?.start()
controller = nil // deinit does not run
RunLoop.current.run(until: Date().addingTimeInterval(0.35))
print("end of run loop")go deeper
Recall that a repeating Timer keeps running until invalidate() is called and that its block can keep self alive.
Trace the chain run loop, timer, block, self, and explain why invalidate() inside deinit can never run while that chain exists.
Fix both halves, weak capture and a defined invalidation point, and explain why leak tools stay silent because the controller is still reachable.
Treat timers, observers and subscriptions as resources with an explicit stop, owned by a lifecycle event, rather than cleanup hidden in deinit.
## The chain that keeps the controller alive A **repeating `Timer`** in Foundation is not owned only by the object that created it. When you call `Timer.scheduledTimer(withTimeInterval:repeats:block:)`, the timer is scheduled on the current **run loop**, and Foundation's documentation says the run loop holds a strong reference to it until `invalidate()` is called. A repeating timer never invalidates itself; a non-repeating one does after it fires. Follow the references from the run loop: 1. The run loop holds the timer. 2. The timer holds its block (a closure is a reference type). 3. The block captures `self` strongly because its body uses `self.saves`. 4. The controller also holds the timer in its own `timer` property, which closes a loop, but the loop is not even needed: steps 1 to 3 are a path from a long-lived root to the controller. When the screen that owns the controller releases it, the controller's strong count does not reach zero. It keeps saving every tick, invisible to the rest of the app. ## Why invalidate() in deinit is a trap `deinit` runs only after the last strong reference is gone. Here the last strong reference is the block, which lives as long as the timer, which lives until `invalidate()`. Putting `invalidate()` in `deinit` makes the cleanup depend on itself: **a `deinit` can never break a cycle that keeps its own object alive.** ## The fix: weak capture plus invalidation Break the edge from block to controller, then stop the timer: - Write `{ [weak self] _ in guard let self else { return } … }`. The block no longer owns the controller, so releasing the controller lets its count reach zero. - Keep `timer?.invalidate()` in `deinit` (it now runs), or call it from an explicit `stop()` when the screen disappears. Invalidation is what makes the run loop drop the timer. - Do not rely on `[weak self]` alone. Without `invalidate()`, the repeating timer keeps firing, each tick finding `self` is `nil`, for as long as its run loop runs. `guard let self` gives the block a strong reference only for the duration of one tick, which is what you want: the controller cannot disappear halfway through a save. The capture-list syntax itself is covered in the Swift material on closures. ## guard let self or optional chaining Inside the block, `self?.saves += 1` would also work for a single statement. `guard let self else { return }` is the better habit once a tick does several steps: the bound `self` stays alive for the whole tick, every step sees the same object, and the early return makes the "owner is gone" path explicit. Neither form keeps the controller alive between ticks, because the strong reference ends when the block returns. ## Variants and what holds self | API | What holds the controller | Fix | |---|---|---| | `scheduledTimer(withTimeInterval:repeats:block:)` | run loop, timer, block, `self` | `[weak self]` in the block plus `invalidate()` | | `scheduledTimer(timeInterval:target:selector:userInfo:repeats:)` | the timer keeps a strong reference to `target` until invalidated | invalidate from an event before deallocation, such as `stop()` | | making the `timer` property `weak` | the run loop still holds the timer and its block | does not help on its own | The block parameter is imported as a `@Sendable` closure, so in Swift 6 language mode capturing a non-`Sendable` controller also draws a warning; that is a data-race diagnostic, separate from the leak. ## Finding it - A `print` in `deinit` that never appears after dismissing the screen is the first sign. - Xcode's memory graph debugger shows the controller still alive and the path that holds it: run loop, timer, block, controller. - Instruments' Leaks and the `leaks` command-line tool report memory that nothing reachable points to. This controller is reachable through the run loop, so they report **no leak**: running the leaking snippet under `leaks --atExit` printed 0 leaks. Look for instances that should not exist rather than for a leak report. ## Checklist - Every repeating timer has an owner that invalidates it at a defined moment. - Timer blocks capture `self` weakly unless the controller is meant to live as long as the timer. - Target-selector timers are invalidated before the owner is expected to deallocate.
- Would declaring the controller's `timer` property `weak` break the cycle instead?No. It removes the controller-to-timer edge, but the path that matters remains: the run loop holds the scheduled timer until it is invalidated, the timer holds its block, and the block holds the controller. Only a weak capture in the block, or invalidating the timer, breaks that path.
- Why don't Instruments' Leaks or the `leaks` tool report this controller?They report memory that nothing reachable points to. This controller is still reachable from the run loop through the timer and its block, so it is not a leak in their sense; the leaking snippet run under `leaks --atExit` reports 0 leaks. You find it as an instance that should not exist, in Xcode's memory graph debugger or by comparing allocation snapshots.
- With `scheduledTimer(timeInterval:target:selector:userInfo:repeats:)`, does `[weak self]` help?There is no block to put a capture list on. Foundation documents that the timer keeps a strong reference to its target until it is invalidated, so the controller lives as long as the timer runs. Invalidate it from an event that happens before the owner lets go, such as an explicit `stop()` when the screen disappears, or switch to the block-based API with a weak capture.
- Calling invalidate() in deinit is enough to stop the timer and free the controller.
- Declaring the timer property weak breaks the retain cycle.
- With [weak self], the repeating timer stops firing once the controller is gone.
- Instruments' Leaks will report the controller as a leak.
- A repeating Timer invalidates itself after each time its block runs.