Debugging Retain Cycles

A couple months ago I gave a presentation on debugging retain cycles at CocoaHeads SLC. It was a quick 15 minute lightning talk but hit on the important topic of retain cycles... those nasty bugs that can be hard to fix and even harder to find in the first place. While worry about memory leaks is mitigated in 2016 due to ARC and use of value types in Swift, it's still very much a concern.

The first question is what are retain cycles? This is a go to iOS interview question and will definitely come up in one way or another, especially if you are early in your career. Other related questions that you could get asked where the interviewer is probably trying to gauge your understanding level:

  • What's the difference between a class and a struct in Swift? When would you use one or the other?
  • What does the weak keyword designate?
  • What are some pros and cons of using closures?

All of these questions have potential memory management - and retain cycle - implications. Starting with the question of what are they, retain cycles are instances of your objects being held in memory longer than intended, resulting in an unnecessary "leak" of memory. Retain cycles may be harmless in nature, or could bog down your entire app in a way that results in crashes or the OS terminating it.

Jumping over to instruments, when profiling your app the below chart is what you do NOT want to see. That is, memory allocations that continue to rise and rise. Instead, as a user navigates through the app you'd expect to see rises and subsequent drops in memory usage.

A good way to test your app is to open Instruments, open the Allocations tool, and being profiling your app. Use the filter bar to filter down to just view controllers or maybe just your root view controller while logged in. Try launching the app, logging in, performing an operation, then logging out. If memory allocations only rise, you likely have some retain cycles causing your view controllers to be persisted when they shouldn't be. What you want to see is the graph level out to the pre-login memory usage levels after logging out.

Continue reading at Weak, Strong, Unowned, Oh My! - A Guide to References in Swift...