In Core Animation, why does a breathing countdown's CADisplayLink keep its view controller alive, and how do you set its frame rate on iOS 15 and later?
answer
- the run loop holds the link
- the link holds its target
- deinit never gets its turn
- invalidate() or a weak proxy
- a range, not a single number
basics
~20 sA CADisplayLink on a run loop is retained by it and retains its target until invalidate(), so an invalidate() in the target's deinit never runs. Invalidate when the countdown stops or use a weak proxy; set preferredFrameRateRange, iOS 15 and later.
solid answer
~50 s`CADisplayLink(target:selector:)` calls the selector in step with the display once `add(to:forMode:)` puts it on a run loop. Apple documents the ownership: while added to a run loop the link is implicitly retained, and `invalidate()` removes it from every mode and releases its target. A view controller that is both owner and target is therefore kept alive through the run loop; its `deinit` cannot fire, so an `invalidate()` placed there never runs and the callback keeps ticking after the screen closes. Call `invalidate()` when the countdown stops or the screen disappears, or target a small proxy that holds the controller weakly and invalidates the link once the controller is gone. For the rate, set `preferredFrameRateRange` to a `CAFrameRateRange(minimum:maximum:preferred:)`, available since iOS 15, which supersedes `preferredFramesPerSecond`. On iPhone, rates above 60 Hz also need `CADisableMinimumFrameDurationOnPhone` set to true in Info.plist.
code
swift · 42 linesimport UIKit
@MainActor
final class DisplayLinkProxy: NSObject {
weak var owner: CountdownController?
init(owner: CountdownController) { self.owner = owner }
@objc func tick(_ link: CADisplayLink) {
guard let owner else {
link.invalidate() // owner is gone: release the proxy and leave the run loop
return
}
owner.step(link)
}
}
@MainActor
final class CountdownController {
private var link: CADisplayLink?
private var endTime: CFTimeInterval = 0
func start(seconds: CFTimeInterval) {
let link = CADisplayLink(target: DisplayLinkProxy(owner: self),
selector: #selector(DisplayLinkProxy.tick(_:)))
link.preferredFrameRateRange = CAFrameRateRange(minimum: 10, maximum: 30, preferred: 30)
link.add(to: .main, forMode: .common)
endTime = CACurrentMediaTime() + seconds
self.link = link
}
func step(_ link: CADisplayLink) {
let remaining = max(0, endTime - link.targetTimestamp)
print(String(format: "%.1f", remaining))
if remaining == 0 { stop() }
}
func stop() {
link?.invalidate()
link = nil
}
}go deeper
Recall that a display link calls you once per frame, and that you must call invalidate() when you are done with it.
Explain the retain chain, run loop to link to target, and why it defeats an invalidate() in deinit; show the weak-proxy fix.
Pick a frame-rate range that matches the content, know the Info.plist key for 120 Hz on iPhone, and compute time from targetTimestamp so the code survives rate changes.
Decide when a feature needs its own display link at all, since Apple recommends as few as possible, versus a layer animation the system paces for you.
## What a display link is A **`CADisplayLink`** is a timer bound to the display's refresh. You create it with `CADisplayLink(target:selector:)`, naming an object and an `@objc` method that takes the link as its argument, then call `add(to:forMode:)` to schedule it on a run loop. From then on, unless `isPaused` is `true`, the method is called once per frame the system renders for it. In the breathing app, a display link drives the countdown label so the tenths of a second change in step with what the screen shows, rather than on a timer that drifts against the frame. Apple's documentation also says not to subclass `CADisplayLink`, and to group animations with similar timing into one link rather than creating one per view. Each callback can read: - **`timestamp`**, the time of the frame associated with the most recent callback; - **`targetTimestamp`**, the time the next frame is expected to be shown, which is what a countdown should compute from; - **`duration`**, the frame interval at the display's maximum rate. The actual interval is `targetTimestamp - timestamp`. ## Who retains whom The ownership is the classic trap, and Apple documents it directly: 1. **The run loop retains the link** while it is added to any mode; removal from the last mode releases it. 2. **The link retains its target** until `invalidate()` is called; `invalidate()` removes the link from all modes and releases the target. 3. If a view controller is the target and expects to call `invalidate()` from its own `deinit`, there is a cycle through the run loop: the run loop keeps the link, the link keeps the controller, and `deinit` never runs. The result is a closed screen whose controller stays in memory and whose callback keeps firing every frame, still updating labels nobody can see and costing power. ## Breaking the cycle - **Invalidate on a lifecycle event,** such as when the countdown finishes, in `viewWillDisappear(_:)`, or for a custom view when `didMoveToWindow()` finds `window == nil`. - **Target a weak proxy.** A small `NSObject` holds the controller weakly and forwards the callback; when the weak reference is `nil`, the proxy invalidates the link. The run loop then retains only the link and the proxy, never the controller. - **`remove(from:forMode:)` is not a substitute.** It releases the link once it leaves its last mode, but only `invalidate()` is documented to release the target. - **Pause instead of tearing down** when the screen will return soon: `isPaused = true` stops callbacks, but the link and its target stay retained, so it does not end the lifetime. ## Frame rate: preferredFrameRateRange | API | Availability | Status in the iOS 27.1 SDK | |---|---|---| | `frameInterval` | iOS 3.1 | deprecated in iOS 10, replaced by `preferredFramesPerSecond` | | `preferredFramesPerSecond` | iOS 10 | superseded by `preferredFrameRateRange`, marked to be deprecated, still works | | `preferredFrameRateRange` | iOS 15 | current: a `CAFrameRateRange` with `minimum`, `maximum` and an optional `preferred` | A range lets Core Animation align the link with other animations on screen. A countdown showing tenths of a second does not need 120 Hz; `CAFrameRateRange(minimum: 10, maximum: 30, preferred: 30)` saves power on a ProMotion display. Rates are hints, not guarantees: - Apple's ProMotion guidance says apps must not assume a specific rate; the system lowers rates in Low Power Mode or when the device is hot. - On iPhone, rates above 60 Hz apply only when the app's Info.plist sets **`CADisableMinimumFrameDurationOnPhone`** to true; iPad Pro needs no key. - Each `CAAnimation` also has its own `preferredFrameRateRange` since iOS 15, for explicit animations that need a hint. ## Run loop modes and newer entry points Adding the link with `forMode: .common` keeps it firing while a scroll view is being dragged; a link in `.default` only pauses during tracking. iOS 27 adds UIKit's `displayLink(target:selector:)` on `UIWindowScene`, which follows the scene when it moves between displays, and deprecates `UIScreen`'s `displayLink(withTarget:selector:)`; `CADisplayLink(target:selector:)` itself is unchanged. How you know it is fixed: closing the breathing screen frees its controller in the memory graph, and the callback stops. Frame budgets as a design concern are covered with mobile performance design; this question is about the link's lifetime and its rate hint.
- Why add the display link in the .common run loop mode rather than .default?While the user drags a scroll view, the main run loop runs in its tracking mode, and a link added only in `.default` gets no callbacks until the drag ends, so the countdown freezes. `.common` covers both the default and the tracking modes, so the link keeps firing during scrolling.
- Why compute the remaining time from targetTimestamp instead of counting callbacks?The callback rate is a hint: the system can lower it in Low Power Mode, under thermal pressure or to align with other animations, and a callback can be skipped when the main thread is busy. Subtracting `targetTimestamp` from a fixed end time stays correct at any rate.
- What does CADisableMinimumFrameDurationOnPhone change for a display link?On ProMotion iPhones, Core Animation will not apply any rate above 60 Hz unless the Info.plist sets this key to true. Without it, a `preferredFrameRateRange` asking for 120 Hz still gets at most 60 callbacks per second. iPad Pro needs no such key.
- A CADisplayLink holds its target weakly, the way a delegate is held.
- Calling invalidate() in the target's deinit is enough to stop the link.
- preferredFramesPerSecond is deprecated and stopped working on iOS 15.
- Setting a range with a maximum of 120 guarantees 120 callbacks per second on ProMotion iPhones.
- Counting display-link callbacks gives an accurate clock for a countdown.
Assumes the iOS 27.1 SDK: preferredFrameRateRange is iOS 15 and supersedes preferredFramesPerSecond, which is marked to be deprecated but not deprecated yet.