Browse Questions
Answer: Xcode's Memory Graph Debugger visualizes live heap allocations and object reference relationships, while Malloc Stack Logging reveals the exact source code line where leaked memory was allocated.
To diagnose memory leaks with Memory Graph Debugger:
- Enable Malloc Stack Logging: Open your scheme (
Product > Scheme > Edit Scheme...), navigate to Run > Diagnostics, and check Malloc Stack Logging (select Live Allocations Only or All Allocations and Free History). - Reproduce the Flow: Run your app, perform the workflow (e.g. push a screen and pop it back).
- Capture Memory Graph: Click the Debug Memory Graph icon (three connected circles) in the Xcode debug bar.
- Identify Leaked Objects: Look in the Debug Navigator for purple exclamation point icons (
!), which indicate confirmed memory leaks detected by Xcode. - Inspect Retain Cycles & Backtraces: Click any leaked object in the navigator to view the node relationship graph. Look for cycles where arrows point between two or more objects. In the inspector pane on the right, view the Backtrace to see the exact file and line where the object was created.
Code Example:
// Example of a retain cycle visible in Memory Graph
class DetailViewController: UIViewController {
var onDismiss: (() -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
// ❌ Leaks DetailViewController upon dismiss:
// onDismiss retains self, self retains onDismiss closure
onDismiss = {
self.analyticsLogDismiss()
}
}
func analyticsLogDismiss() { print("Dismissed") }
}
// LLDB command during Memory Graph inspection to inspect address:
// (lldb) po [0x600003b54200 description]
// (lldb) malloc_history 0x600003b54200
Key Points:
- Memory Graph Debugger works on both iOS Simulator and physical devices
- Filtering by workspace symbols (bottom search bar: check the small person icon) hides UIKit system internal objects and highlights your app's classes
- Malloc Stack Logging enables
malloc_history <address>in LLDB to inspect allocation call trees