Native iOS memory leaks rarely surface where you create them. A retain cycle can hide behind a screen users open once, while the production symptom is rising memory pressure after several background and foreground transitions.
The fix is a workflow, not a single tool: use MetricKit’s on-device telemetry to find the problem in the field, Xcode Instruments and the Memory Graph debugger to prove which object stays alive, then a repeatable Swift 6 test to confirm the repair.
This workflow separates two questions developers often mix up: where your users experience memory pressure and which object keeps the memory alive. MetricKit answers the first across real devices. Instruments and Xcode answer the second on a controlled build.
Start With the Production Signal
MetricKit tells you whether memory pressure is a field problem before you try to reproduce it locally. It delivers performance metrics and diagnostics from your users’ devices through daily metric payloads and diagnostic payloads.
Two metric families matter most for memory work:
MXMemoryMetricreportspeakMemoryUsageandaverageSuspendedMemoryfor the app.MXAppExitMetriccounts how the app was terminated. In the background,cumulativeMemoryPressureExitCountandcumulativeMemoryResourceLimitExitCountshow memory-related terminations. In the foreground,cumulativeMemoryResourceLimitExitCountshows the app crossing its memory limit while your user was looking at it.
For an iOS app that has shipped, look for these patterns:
- Peak memory rises from one app version to the next.
- Memory-related exits increase without a matching rise in conventional crashes.
- A specific device class or OS version reports more memory pressure.
- A screen, import, scan, or media workflow correlates with the issue.
MetricKit isn’t a heap graph. It won’t tell you that ProfileViewModel owns a closure that retains ProfileViewController. It gives you the production evidence you need to choose a scenario worth reproducing.
Capture MetricKit Payloads in Swift 6
Register one MXMetricManagerSubscriber early in the app lifecycle and persist the payloads in a form your team can inspect.
import MetricKit
import OSLog
final class MetricKitReporter: NSObject, MXMetricManagerSubscriber {
private let logger = Logger(subsystem: "com.example.app", category: "metrics")
func start() {
MXMetricManager.shared.add(self)
}
func didReceive(_ payloads: [MXMetricPayload]) {
for payload in payloads {
if let memory = payload.memoryMetrics {
logger.info("Peak memory: \(memory.peakMemoryUsage.converted(to: .megabytes).value) MB")
}
if let exits = payload.applicationExitMetrics {
let background = exits.backgroundExitData
logger.info("Background memory pressure exits: \(background.cumulativeMemoryPressureExitCount)")
logger.info("Background memory limit exits: \(background.cumulativeMemoryResourceLimitExitCount)")
logger.info("Foreground memory limit exits: \(exits.foregroundExitData.cumulativeMemoryResourceLimitExitCount)")
}
upload(payload.jsonRepresentation(), kind: "metrics")
}
}
func didReceive(_ payloads: [MXDiagnosticPayload]) {
for payload in payloads {
upload(payload.jsonRepresentation(), kind: "diagnostics")
}
}
private func upload(_ data: Data, kind: String) {
// Queue an authenticated upload. Avoid blocking the callback.
}
}
Keep the callback small. Attach your app version and an internal scenario identifier if you have one, then hand the work to a background upload queue. Never log the complete payload if it can contain user or device data.
Check the availability of each part against your deployment target. MXMetricManager and memory metrics arrived in iOS 13. MXDiagnosticPayload and app exit metrics require iOS 14. If your app targets iOS 14 or later, you need no availability checks at all.
The reporter must live as long as the process. A local object created inside an initializer can be released immediately, so make it an application-owned dependency:
import SwiftUI
import UIKit
final class AppDelegate: NSObject, UIApplicationDelegate {
private let metricKitReporter = MetricKitReporter()
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
metricKitReporter.start()
return true
}
}
@main
struct ExampleApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
var body: some Scene {
WindowGroup { ContentView() }
}
}
Read the Payload Without Overclaiming
MetricKit payloads help you rank the problem, but a payload field is not automatically a leak diagnosis. Use the payload to answer four operational questions:
- Which app version shows the regression?
- Which device and OS combinations are affected?
- Does memory pressure cluster around a release, feature, or workflow?
- Can you reproduce the same sequence with a test account and deterministic data?
For repeatable analysis, store the raw JSON and normalize only the fields you need for dashboards. Keep the original payload available so a developer can inspect the context later. Apple’s MXMetricPayload documentation lists the payload properties and their data types.
Do not call every high-water mark a leak. A cache can grow by design, a decoded image can be released later, and the system reclaims memory differently across devices. A leak is a lifetime problem: objects remain reachable after the feature should have released them.
Reproduce the Growth With Xcode Instruments
Xcode Instruments answers whether memory grows during a controlled run and which allocations contribute to that growth. Open Product > Profile and choose the Leaks or Allocations template. Apple’s Instruments documentation covers the profiling workflow.
Use a short scenario you can repeat ten or more times:
- Launch the app from a clean state.
- Reach the screen just before the target workflow.
- In Allocations, click Mark Generation to set a baseline.
- Enter the workflow, load its data, and leave it.
- Click Mark Generation again, then repeat steps 4 and 5 several times.
- Compare the growth column of each generation.
Generation analysis is the key measurement. Each generation lists the objects allocated since the previous mark that are still alive. If every iteration leaves behind the same view model, view controller, or task, you have a leak that compounds with each navigation. A single large allocation that never repeats is usually expected.
Separate Allocation Growth From Retained Growth
The Allocations instrument shows what your process allocated. The Memory Graph debugger shows what remains reachable. You need both because they expose different parts of the problem.
In Allocations, inspect:
- Persistent bytes in each generation.
- The responsible library or source location.
- Growth in
Data, image, task, view controller, and view model objects. - Whether an autorelease boundary changes the result.
If allocations rise but return after the workflow finishes, investigate caching, autorelease behavior, or delayed cleanup before changing ownership. If the same instances survive every iteration, open the Memory Graph.
Use the Xcode Memory Graph to Prove Ownership
The Memory Graph debugger answers the question a memory counter cannot: what path keeps this object alive? Apple describes it in Diagnosing memory, thread, and crash issues early.
Before you start, enable Malloc Stack Logging (Live Allocations Only) in your scheme’s Diagnostics settings. The graph then shows the backtrace where each object was allocated, which turns “something leaks” into a file and a line.
Pause the app after leaving the target screen, click Debug Memory Graph, and search for an instance you expect to be gone. Inspect the retaining path from the object back to a root. Common paths include:
- A view controller retains a view model, and the view model’s closure retains the view controller.
- A notification observer retains an object that never unregisters.
- A
Taskcaptures a view controller or service for longer than the screen’s lifetime. - A delegate is declared strongly even though the owner and delegate refer to each other.
- A Combine subscription or callback remains in a set owned by a long-lived service.
The graph is most useful when you name the expected lifetime first. A detail screen should disappear after its navigation controller releases it. If the graph shows a singleton, task, timer, or subscription holding it, you have a concrete repair target.
Fix the Ownership Bug in Swift 6
Most native iOS memory leaks come from an ownership relationship that doesn’t match the feature’s lifetime. Fix the relationship, not the symptom.
Break Closure Cycles Deliberately
A closure stored by an object must not strongly capture the object that owns it unless the cycle is intentional and eventually broken.
@MainActor
final class DetailViewModel {
var onUpdate: (() -> Void)?
func connect(to service: DataService) {
service.onChange = { [weak self] in
self?.onUpdate?()
}
}
}
weak is not a universal fix. If the callback must keep a dependency alive, make that lifetime explicit. If the closure can outlive the screen, clear it when the screen goes away.
Cancel Tasks When the Owner Disappears
Swift concurrency makes asynchronous ownership easier to express, but a task still retains what it captures. A common mistake is to write guard let self at the top of the task: from that point, self is strong for the entire await, and the weak capture protects nothing. Resolve self only after the suspension point, and cancel the task when the feature ends.
@MainActor
final class DetailViewModel {
private var loadTask: Task<Void, Never>?
func load() {
loadTask?.cancel()
loadTask = Task { [weak self] in
let value = await fetchValue()
guard !Task.isCancelled, let self else { return }
self.apply(value)
}
}
func stop() {
loadTask?.cancel()
loadTask = nil
}
}
Call stop() from the feature’s teardown path. While fetchValue() is suspended, the task holds no strong reference to the view model, so the screen can be released. Cancellation then stops unnecessary work from continuing.
Make Delegates Weak and Observers Finite
Delegates are usually non-owning relationships. Mark class-bound delegates as weak when the delegate shouldn’t extend the owner’s lifetime. For notifications, keep a token you can remove or use a registration scoped to the object’s lifetime. For timers, invalidate them and clear their closures.
protocol DataServiceDelegate: AnyObject {
func serviceDidUpdate()
}
final class DataService {
weak var delegate: DataServiceDelegate?
}
A leak fix is incomplete until the teardown path is visible in code review. Ask who owns each task, observer, timer, subscription, cache, and callback, then ask when each one releases its owner.
Validate the Fix Instead of Trusting the Graph
The best validation is a before-and-after trace using the same device, build configuration, dataset, and scenario. A useful regression check has four layers:
| Layer | Question | Evidence |
|---|---|---|
| MetricKit | Did field memory pressure change after release? | Peak memory and memory exit counts by app version |
| Instruments | Does retained memory stabilize across repetitions? | Generation analysis with no repeating survivors |
| Memory Graph | Is the feature object released? | No unexpected retaining path |
| XCTest | Does the fix stay fixed? | XCTMemoryMetric baseline in a UI test |
Turn the reproduction into an automated performance test with XCTMemoryMetric. Xcode records a baseline and flags the test when physical memory grows beyond it:
import XCTest
final class DetailMemoryTests: XCTestCase {
func testDetailScreenReleasesMemory() {
let app = XCUIApplication()
app.launch()
measure(metrics: [XCTMemoryMetric(application: app)]) {
app.buttons["Open detail"].tap()
app.navigationBars.buttons.element(boundBy: 0).tap()
}
}
}
If the feature processes large media or scan data, use a representative fixture instead of a tiny mock that never reaches the same memory path.
Keep the fix narrow. Don’t replace every closure with weak, disable caching blindly, or move all work into detached tasks. Those changes can hide ownership bugs, reduce correctness, or create data races. Find the retaining path, align ownership with the feature lifetime, and measure again.
When to Bring In a Native iOS Team
Memory leaks are rarely one bug. They usually reveal an ownership model that grew without a plan as the app added features, teams, and dependencies. If your MetricKit data shows memory exits climbing and your team can’t spare the time to trace them, an outside review can be faster than another release cycle of guesswork.
Sidekick Interactive has built and maintained native iOS and Android apps in Montreal since 2011, for clients such as TouchTunes, ABB, HP, Dassault Systèmes, Daimler, Flo, Intelcom, and Shoppers Drug Mart, as well as the city’s INFO-Neige MTL snow removal app. Our engineers work in Swift and Kotlin every day, and app maintenance is part of what we deliver, not an afterthought. If your app is losing users to memory terminations.
FAQ
How Do I Check for a Memory Leak in Xcode?
Profile the app with the Allocations or Leaks instrument, repeat the same workflow several times, and use Mark Generation between iterations. If each generation leaves the same feature objects alive, open the Memory Graph debugger after the feature closes and inspect the retaining path that keeps those objects reachable.
Does Xcode Instruments Detect Every iOS Memory Leak?
No. Instruments shows allocation and retention patterns only during the scenario you actually run, so it can’t observe a workflow you never reproduce. Pair local traces with MetricKit production telemetry to investigate device, OS, and release patterns that never appear in a developer session on your own test devices.
What Is the Difference Between MetricKit and Xcode Instruments?
MetricKit reports aggregated performance and diagnostic payloads from real app installations, while Instruments profiles a controlled run on a development device or simulator. MetricKit tells you where to look in production. Instruments and the Memory Graph debugger then tell you which object is retaining memory on your local build.
Can Swift Concurrency Cause Memory Leaks?
Yes. A Task retains the values it captures while it runs, and an async callback can keep a feature alive beyond its intended lifetime. Store your tasks, cancel them during teardown, resolve weak references only after each await, and inspect captures whenever a view model or controller survives unexpectedly.
How Do I Fix an iOS Memory Leak Caused by a Closure?
Inspect the retaining path in the Memory Graph first, then break the cycle with a weak or unowned capture only when that lifetime is correct for the feature. Also clear stored callbacks or cancel the underlying operation when the owning screen ends, so the closure cannot keep it alive later.
What Is the Memory Graph Debugger Used For?
It visualizes live object relationships and shows the retaining paths to objects that should already have been released. With Malloc Stack Logging enabled, it also shows where each object was allocated. Use it after reproducing the same flow several times, not as a substitute for a production memory signal.
Related Articles
- 8 Common Mobile App Development Challenges and Solutions
- How to Design Apps for Better Battery Efficiency
- Gesture Navigation in Mobile Apps: Best Practices
Sources & References
- Apple MetricKit documentation for production metrics and diagnostics
- Apple MXMemoryMetric for peak and suspended memory
- Apple MXAppExitMetric for memory-related termination counts
- Apple MXMetricPayload for payload structure
- Apple MXMetricManager for subscriber setup and availability
- Apple MXDiagnosticPayload for diagnostic payloads
- Apple Instruments documentation for allocation profiling
- Apple memory and crash diagnostics for Memory Graph workflows
- Apple XCTMemoryMetric for automated memory regression tests