Diagnose Memory Leaks Using Xcode Instruments

The leaks instrument might become your best friend when facing memory issues

Zafar Ivaev
Feb 13 · 3 min read

In this short tutorial, we’ll learn how to produce and accurately identify a memory leak using Xcode’s debug memory graph and leaks instrument.

The example app shows two screens. On the first screen, a button, on tap, let’s us navigate to the second screen, where we intentionally create a memory leak using a retain cycle.

Here’s our workflow:

  • We open the Xcode leaks instrument first and press the record button
  • When the app automatically launches, we press on the navigate button that presents our leaking view controller
  • We simply pop it using navigation item’s back button
  • Finally, we observe the effect in the leaks instrument and memory graph.

The source code is available on GitHub.


Let’s Start

All it does is present our target leaking view controller:

To create a retain cycle, we have a ViewComponent class that takes a UIViewController as a parameter:

As a result, we have the following relationship:

LeakingViewControllerViewComponent

ViewComponentLeakingViewController

For an object to be released from memory, no other object should be pointing or holding it, which, of course, isn’t what’s happening in our example.


Diagnose the Memory Leak

  • Choose “Xcode” in the top left of the screen
  • Expand “Open Developer Tool,” and select “Instruments”
  • Now choose “Leaks,” and make sure you have chosen your target app and device at the top (“Choose a profiling template for…”):
  • Finally, press the record button

Now our app launches, and all we need to do is tap on the navigate button and then on the back button of the LeakingViewController.

We have the following result:

The red icon means we’ve leaked memory somewhere. To see the actual not-allocated objects, we’ll use Xcode’s memory graph tool:

We can see that even though we presented and dismissed the LeakingViewController, it’s still in the memory graph along with the ViewComponent:


Wrapping Up

Thank you very much for reading!

Better Programming

Advice for programmers.

Zafar Ivaev

Written by

iOS Developer

Better Programming

Advice for programmers.

More From Medium

More from Better Programming

More from Better Programming

More from Better Programming

Why Do Incompetent Managers Get Promoted?

1.3K

More from Better Programming

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade