In a meal-kit iOS app, memory climbs each time the recipe screen opens and closes; how do you find and confirm a retain cycle with Xcode's memory graph and Instruments?
answer
- the Memory gauge never comes back down
- count instances after closing the screen
- Focus on Node, strong references
- Malloc Stack for allocation backtraces
- Leaks versus Allocations generations
basics
~20 sAfter opening and closing the screen, click Debug Memory Graph and look for its objects still listed. Focus on one node: strong references that loop back to it form a retain cycle. Instruments' Leaks and Allocations templates confirm the fix.
solid answer
~50 sWatch the **Memory** gauge in the Debug navigator while opening and closing the recipe screen; usage that rises and never falls means a leak or abandoned memory. Click **Debug Memory Graph**: the navigator lists types by library with their instances, so three closed screens leaving three `RecipeStepModel` instances is the evidence. Select one and use **Focus on Node**; the graph highlights strong references, and if the object it points at holds a strong reference back, that is a retain cycle, often a stored closure capturing `self`. Enable **Malloc Stack** in the scheme's Diagnostics to see each node's allocation backtrace. Break the cycle with a `weak` capture or by removing the reference, then retest; in Instruments, the **Leaks** template checks for leaked memory and the **Allocations** Generations view, between two Mark Generation clicks, shows anything the screen still holds.
code
swift · 14 linesfinal class StepTimer {
var onTick: (() -> Void)?
func fire() { onTick?() }
}
final class RecipeStepModel {
let timer = StepTimer()
private(set) var secondsLeft = 600
init() {
// The model owns the timer and the timer's closure owns the model.
timer.onTick = { self.secondsLeft -= 1 }
}
}go deeper
Know where the Memory gauge and the Debug Memory Graph button are, and that rising memory that never falls needs investigating.
Walk through counting instances, Focus on Node and strong references, and explain the leak versus abandoned memory difference.
Reproduce on a device, prove a cycle with the graph and Malloc Stack backtraces, fix it, and confirm with Leaks and Allocations generations.
Decide which screens get a memory round-trip check before release and how leak findings are triaged against feature work.
## Leak or abandoned memory Apple's debugging guide separates two problems that look the same on a graph: - A **memory leak** caused by a **retain cycle**: objects hold strong references to each other but the app no longer references any of them, so nothing can free them. - **Abandoned memory**: the app still references objects it will never use again, such as a cache that only grows. Both show up as memory that keeps rising. The tools differ in which one they catch, so name which you are looking for. ## Step 1: reproduce with the Memory gauge Run the app from Xcode and open the Debug navigator. The **Memory** gauge shows current use and the highest value seen. Open the recipe screen, cook through a step, close it, and repeat a few times. Memory should rise when the screen is presented and fall when it is dismissed. If it climbs on every round trip and never returns, keep going. Two cautions from Apple's memory guide. In the **Simulator** the gauge stays in the green because macOS issues no memory warnings or out-of-memory terminations, so green there does not mean safe on a device. And device profiling gives higher-fidelity numbers than the Simulator. ## Step 2: inspect the memory graph Click **Debug Memory Graph** in the debug bar; the app pauses. The Debug navigator now lists types, grouped by library, each with its instances, called **nodes**. Use the filter to find the screen's types. 1. Count instances. After three round trips, a closed screen should leave none of its per-visit objects; three `RecipeStepModel` nodes is the bug in front of you. 2. Select a node. Its graph shows every reference to it and **highlights strong references**. 3. Control-click the node holding the strong reference and choose **Focus on Node**. If that object is in turn strongly referenced by the first, the two form a retain cycle. 4. Click a reference to see its details: the variable name, the kind of reference, and the source and destination objects. To tie a node to code, enable **Malloc Stack** in the Diagnostics section of the scheme's Run action before launching; the inspector then shows the call stack that allocated each node. **File > Export Memory Graph** saves the graph for a teammate or for the `leaks` and `vmmap` command-line tools. ## Step 3: fix and verify In the code sample, the model owns a `StepTimer`, and the timer's stored `onTick` closure captures `self` strongly, so each owns the other. Capturing `self` weakly breaks the cycle; removing the reference also works when the timer does not need the model. The rules of capture lists belong to the Swift language material; the Xcode part is proving the fix: repeat the round trips and check that the instance count drops back. ## Step 4: confirm in Instruments Apple's performance guide points memory issues to the **Allocations** and **Leaks** templates: | Tool | What it answers | |---|---| | Leaks template | is there leaked memory, which the app no longer references, such as a cycle? | | Allocations, Generations | what did this feature allocate that is still alive? | | Memory graph | who holds this object, and how? | | Memory gauge | is usage rising over time at all? | For **Generations**: launch, navigate to just before the recipe screen, click **Mark Generation**, open and close the screen, then click **Mark Generation** again. The second generation lists what the round trip allocated and still keeps, which catches abandoned memory that no leak check reports, because the app still references it. ## Catching it before users do - The memory report's gauge has a yellow region, where use is high enough to trigger a warning, and a red region, where iOS may terminate the app; a leak that survives a long cooking session ends there. - The scheme's **Memory Graph on Resource Exception** diagnostic captures a memory graph when the app hits a resource limit, so the evidence exists even when nobody was watching the gauge. - The Organizer's Memory pane reports peak memory and memory at suspension from the field, split by device type and by the 50th and 90th percentile. ## What not to reach for - **Zombie Objects** finds messages sent to objects already released, the opposite problem. - **Address Sanitizer** does not detect memory leaks, as Apple's documentation states. - The SwiftUI instrument for finding views that redraw too often is covered with SwiftUI performance; it is not a leak tool.
- The memory graph shows no cycle, yet memory still grows per visit. What next?Suspect abandoned memory: something still referenced, such as an image cache keyed by recipe that is never trimmed. Use the Allocations instrument's Generations view around one round trip to list what the visit allocated and kept, then decide when the app stops needing it and remove that reference.
- How do you see which line of code created a leaked node?Enable Malloc Stack in the scheme's Run action, Diagnostics section, before launching. With allocation stack traces on, the memory graph inspector shows the call stack recorded when the selected node was allocated, which leads to the function that created it.
A retain cycle is two diners each waiting for the other to leave first: nobody else is at the table, yet it is never cleared.
- A green Memory gauge in the Simulator proves there is no problem
- Zombie Objects is the tool for finding leaks
- Address Sanitizer reports leaked objects
- Every object still in memory after closing a screen is a leak
- The Leaks instrument catches caches that only grow