Detect Memory Leaks in iOS Mobile Application
Memory related issues, a.k.a. memory leaks, are one of the most common problems in iOS coding. Encountering such an issue is usually nightmare for an iOS developer, due to its incredible difficulty of spotting and figuring out the root cause. Luckily, we have multiple tools and powerful IDE to track down memory leaks, and in this article we will introduce 3 of them.
FBRetainCycleDetector
It is an open source library launched by Facebook in 2016 F8 Conference. Its goal is to detect all possible retain cycles in Objective-C codebase during runtime. For how to use it, let’s take a look at following example:
From above code we could notice a retain cycle existing between ViewController and its block. Now let us import FBRetainCycleDetector (via CocoaPods/Carthage) and use it to find the retain cycle:
Then it will print retain cycle info in the console as below:
The good thing of FBRetainCycleDetector is its easy learning curve. However, FBRetainCycleDetector can only look for cycles no longer than 10 objects by default, and it does not support Swift at all.
Debug Memory Graph
Actually, Xcode offers us a native way — debug memory graph to detect memory leaks. It is a tool first introduced in Xcode 8 and is able to grab leaks such as retain cycles. What you need to do is just click memory debug button in Xcode’s debug bar:
Allocations and Leaks Instrument
Instruments are powerful debugging and profiling tools that comes prepackaged with Xcode. For memory issues, we usually use allocations and leaks tools. Allocations instrument tracks all of the objects that app allocates over the course of its run; leaks instrument checks all memory and figures out the leaked objects. Compared to debug memory graph, these instruments offer a more in-depth look into memory leaks.
Here is a simple use case to debug the app:
Allocations instrument tells all the memory usage of the app in the first line; leaks instrument, on the second line, makes a snapshot of memory info every few seconds. At the bottom is the detail panel, which displays useful statistics and call stack to narrow down root cause that triggers memory leaks.
Conclusion
Usually the first step to fix a memory leak issue is to use memory debug graph to detect simple retain cycles, as it is very directive and offers enough information to debug. For a more complicated case, e.g. a retain cycle with more than 10 nodes, using instrument tools may be a better way to trouble shoot since the panel shows call stack and memory usage in detail. As for FBRetainCycleDetector, it directly provides the answer without any extra work from developer side; hence we highly recommend using it in Objective-C environment.
reference : medium
#IOS #IOS_development
Lead Engineer (iOS) @ Dainik Bhaskar, devswiftable.com
6 年Very useful content. Keep it up !!