Memory climbs on the vitals screen
HIGH1. Reproduce
- Open the Vitals monitor, go back. Repeat 5 times.
- Watch the memory number on the screen and in Xcode (Debug Navigator, Memory).
- No heap tool? Open Black Box > Live objects. Count VitalsMonitor.
2. Tools to try
3. Files
Stuck? Open one hint at a time
Hint 1
Use the Memory gauge, then press the Debug Memory Graph button (three connected circles) in the debug bar.
Hint 2
In the memory graph filter for VitalsMonitor. Count them. In the Console search the log for 'VitalsMonitor'.
Hint 3
Something keeps each monitor alive after you leave the screen. Look at the timer and what its closure captures.
Show the answer (try first!)
Root cause
- A repeating Timer keeps its closure. The closure captures
selfstrongly. The timer is never stopped. - The run loop holds the timer. The timer holds the closure. The closure holds the monitor. So the monitor never leaves memory.
How to PROVE it (what you should see)
- Black Box > Live objects:
VitalsMonitor: 5 aliveafter 5 visits. It should be 0 or 1. - Console: filter
VitalsMonitor. You see 5initlines and 0deinitlines. - Debug Memory Graph: 5 VitalsMonitor objects. Click one. The arrows lead to a Timer and a closure.
- Memory gauge grows about 400 KB per second for every leaked monitor.
Fix
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in
guard let self else { return }
self.chartBuffers.append(Data(repeating: 1, count: 200_000))
self.onTick?()
}
func stop() {
timer?.invalidate()
timer = nil
}
// call monitor.stop() from .onDisappearPrevent it next time
- Log
deinitfor long-lived objects. - Stop timers and tasks when the screen goes away.
- Run the Leaks instrument before release.
One-line summary
I filtered the memory graph for the type, saw 5 leaked instances, and followed the arrows to a timer closure that captured self strongly.