skip to content

Cycles and Weak References

Two objects, or an object and its closure, that hold each other strongly never deallocate; weak or unowned breaks the cycle. Interviewers ask when unowned crashes and how you find a leak.

on this pageshow

explore

questions

5

In Swift, why do a screen and the view model it owns never deinit when the view model's delegate holds the screen strongly?

level: juniorimportance: must knowfreq 80%

answer

  1. two holders, neither count hits zero
  2. the back-pointer is the problem
  3. owner strong, back-reference weak
  4. class-bound delegate protocol

basics

~20 s

Each object keeps the other's strong reference count above zero, so ARC never deallocates either and neither deinit runs. Declaring the view model's delegate as weak var breaks the cycle: the screen is freed first, then the view model it owned.

solid answer

~40 s

ARC frees a class instance only when its last strong reference goes away. The screen's `viewModel` property is strong, and if the view model's `delegate` property is strong too, the two form a **strong reference cycle**: when the app releases the screen, each object is still held by the other, so neither `deinit` runs and both stay in memory for the rest of the process. The fix is to make the back-reference non-owning: `weak var delegate: ProfileViewModelDelegate?`. The owning edge (screen to view model) stays strong; the back-pointer (view model to screen) is weak, reads `nil` once the screen is gone, and needs a class-bound protocol (`: AnyObject`) because `weak` applies only to class instances.

code

swift · 20 lines
swift
protocol ProfileViewModelDelegate: AnyObject {
    func profileDidLoad(name: String)
}

final class ProfileViewModel {
    weak var delegate: ProfileViewModelDelegate?   // remove `weak` and neither deinit runs
    func load() { delegate?.profileDidLoad(name: "Ada") }
    deinit { print("ProfileViewModel deinit") }
}

final class ProfileScreen: ProfileViewModelDelegate {
    let viewModel = ProfileViewModel()             // the screen owns its view model
    init() { viewModel.delegate = self }
    func profileDidLoad(name: String) { print("show \(name)") }
    deinit { print("ProfileScreen deinit") }
}

var screen: ProfileScreen? = ProfileScreen()
screen?.viewModel.load()   // prints "show Ada"
screen = nil               // prints "ProfileScreen deinit", then "ProfileViewModel deinit"

go deeper

for a junior

Recall that a strong reference keeps an object alive and deinit runs only when the last one goes. Say which edge becomes weak: the delegate back-pointer, never the owner.

for a middle

Walk through the counts: who holds whom, why neither reaches zero, and how a weak delegate changes the order in which the two objects are freed.

for a senior

Show how you would prove it: deinit prints or the memory graph debugger, and the observers or timers a leaked screen keeps running behind the user's back.

for a principal

Frame it as an ownership convention the codebase follows: owners hold strongly, back-references are weak and class-bound, and a dismissed screen must deinitialize.

## What ARC counts Swift manages class instances with **Automatic Reference Counting (ARC)**. Every property, constant or variable that holds a class instance makes a **strong reference** to it by default, and ARC keeps the instance alive while at least one strong reference exists. When the last one goes away, ARC runs the instance's `deinit` and frees its memory. Structures and enumerations are value types and are not reference-counted, so everything in this answer is about classes. ARC has no tracing step. It never walks the object graph to ask whether something is still reachable from the running program; it only reacts to counts. That is the root of the problem below. ## How a screen and its view model form a cycle A typical screen owns its view model, and the view model reports back to the screen through a delegate: - `ProfileScreen` has `let viewModel = ProfileViewModel()`, a strong reference from screen to view model. - `ProfileViewModel` has `var delegate: ProfileViewModelDelegate?`, and the screen sets `viewModel.delegate = self` in its initializer. If `delegate` is an ordinary stored property, it is a strong reference from the view model back to the screen. Now each object holds the other strongly. When the navigation code drops its reference to the screen, the screen's count does not reach zero (the view model still holds it), and the view model's count does not reach zero (the screen still holds it). Neither `deinit` runs. This is a **strong reference cycle**, and both objects, plus everything they hold, stay allocated until the process ends. The compiler does not reject this code. Each declaration is legal on its own; the leak only exists at run time, in the shape of the object graph. ## Breaking it with a weak delegate The fix is to make one edge **non-owning**. Mark the back-reference `weak`: ```swift protocol ProfileViewModelDelegate: AnyObject { func profileDidLoad(name: String) } final class ProfileViewModel { weak var delegate: ProfileViewModelDelegate? } ``` A **weak reference** does not keep its object alive. When the app releases the screen, the only remaining strong reference to it disappears, so the screen deinitializes. Its stored properties are released with it, the view model's count reaches zero, and the view model deinitializes too. ARC sets the weak `delegate` to `nil` when the screen is deallocated, so a late call such as `delegate?.profileDidLoad(name:)` simply does nothing. Two rules come with `weak`: 1. The property must have an **optional** type, because ARC may set it to `nil`. 2. The protocol must be **class-bound** (`: AnyObject`), because only class instances can be referenced weakly. Without it the compiler reports that `weak` must not be applied to a non-class-bound protocol type. The lesson on protocol requirements covers that rule in detail. ## Which side should be weak | Edge | Reference | Why | |---|---|---| | Screen to view model | strong | The screen creates and owns it; nothing else keeps it alive | | View model to screen (delegate) | `weak` | A back-pointer; the screen may close first | | Navigation stack to screen | strong | Decides how long the screen lives | Making the **owning** edge weak is the opposite mistake: if the screen held its view model weakly and nothing else did, the new view model would be released immediately. The compiler even warns about `weak var viewModel: ProfileViewModel? = ProfileViewModel()` that the instance will be immediately deallocated. ## Seeing it happen - Put a `print` in each `deinit` while you investigate. With the strong delegate, dismissing the screen prints nothing; with `weak`, it prints the screen's line and then the view model's. - Xcode's memory graph debugger shows each live instance and the references keeping it alive, so a dismissed screen still listed there, with an arrow from its view model, is the cycle in picture form. ## Common mistakes - Assuming ARC frees a pair that nothing outside can reach; it only counts. - Marking both references weak, which frees the view model as soon as it is created. - Declaring the delegate weak without `: AnyObject` on the protocol, which does not compile. - Treating a missing `deinit` print as harmless; the leaked screen often keeps observers and timers running.

  • Why doesn't clearing `viewModel.delegate = nil` in the screen's `deinit` fix the strong version?
    Because that `deinit` is exactly what the cycle prevents from running. ARC calls `deinit` only after the last strong reference is gone, and the strong delegate is one of those references. Cleanup in `deinit` can release other resources, but it can never break a cycle that includes the object itself; the reference has to be non-owning from the start, or be cleared by an event that happens before deallocation.
  • What happens if the view model calls its delegate after the screen has been deallocated?
    Nothing. ARC sets a weak reference to `nil` when its object is deallocated, so `delegate?.profileDidLoad(name:)` short-circuits through optional chaining. You never get a dangling pointer from `weak`, only a skipped call, which is why the property must be optional.

  • ARC notices that two objects only point at each other and frees them.
  • Making both the viewModel and the delegate references weak is the safest fix.
  • Setting the last outside variable to nil runs deinit even inside a cycle.
  • Any protocol type can be used for a weak delegate property.
  • The compiler reports an error when two stored properties form a cycle.
open as a page

In Swift, when do you declare a back-reference `unowned` instead of `weak`, and what happens if it is read after its object is gone?

level: middleimportance: must knowfreq 72%

basics

~20 s

Use unowned when the referenced object always lives at least as long as the holder, so it never needs to be nil. Reading an unowned reference after its object is destroyed traps; unowned(unsafe) drops that check and reads freed memory.

open as a page

In Swift, why must a `weak` reference have an optional type, and what did Swift 6.3's `weak let` change about it?

level: middleimportance: should knowfreq 40%

basics

~20 s

ARC sets a weak reference to nil when its object is deallocated, so its type must be optional. Weak used to require var; Swift 6.3's weak let (SE-0481) allows an immutable weak property, which a final Sendable class can hold.

open as a page

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?

level: seniorimportance: should knowfreq 50%

basics

~20 s

The 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.

open as a page

As lead of a Swift app team, how would you catch retain cycles before a release ships, and where would you still allow `unowned`?

level: principalimportance: should knowfreq 35%

basics

~20 s

Layer the defences: an ownership rule enforced in review, deinit-based leak tests for each screen flow, the compiler's capture warnings made errors, and a memory-graph pass on key flows before release. Allow unowned only where the owner provably outlives the holder.

open as a page