How to fix memory leaks in iOS applications?

2020-04-17 05:28发布

问题:

I have found few memory leaks when I am running my application. For your reference, I am sharing the screenshots of Instrument debug logs and also Xcode Debugg memory graph tool. I am not getting what is going wrong here. Please help me to resolve memory leaks.

Please help me to fix the memory shows in the image. Thank you.

回答1:

You do NOT need to use Instruments. That's the old way. Use Xcode itself.

See Visual Debugging with Xcode - 24:45

Watching the video is a MUST, but the summary of the video is as such:

There are two type of memory problems. You just have to repeat a flow in your app 2-3 times to be certain the memory graph has caught it

  • Leaks. Xcode will annotate this with purple icon. Possible are: delegates, closures
  • Abandoned memory. Xcode will not annotate this. But it's still increases your memory footprint. possible examples are: A repeating timer that is never invalidated, NotificationCenter, A never ending DispatchWorkItem

For Leaks the memory graph is a loop ie two way.

For Abandoned memory the graph is NOT two way. It's just an object one that Apple categorizes as 'root path' referencing your object and never letting it go. For more on this see here



回答2:

Memory on mobile devices is a shared resource. Apps that manage it improperly run out of memory, crash, and suffer from drastically decreased performance. so to fix it follow this steps Open Xcode and build for profiling. Launch Instruments. Use the app, trying to reproduce as many scenarios and behaviors as possible. Watch for leaks/memory spikes. Hunt down the source of the memory leaks. Fix the problem.



回答3:

In your memory debugger graph, you have to determine which classes reference each other for example:

Entry Controller Home Controller Feed Controller Entry Controller Home Controller

Can you see how the above code has a cycle between the home controller and entry controller.

You have to determine which one is a weak reference and which one is a strong reference, in other words which one is being retained in memory and which one should be let go.

Hopefully that helps. Feel free to comment if you need further clarification.