Diagnose Memory Leaks Using Xcode Instruments
The leaks instrument might become your best friend when facing memory issues
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.
Suppose we have a simple
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:
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
Now, it’s time to open the leaks instrument:
- 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
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
Xcode’s leaks function is a very handy tool. We can simply press on the record button and navigate and perform actions throughout a large app, and the instrument will document new leaks in the report. We also have a way to save the recording and review it in the future:
Thank you very much for reading!