Search code examples
iosxcodeautomatic-ref-countinginstrumentsretain-cycle

Dealing with strong reference cycles in Xcode 6.4


Recently, I’ve received a quite large and ugly legacy code written in Swift 1.2 with full of singletones and managers referencing to each other. One of my task is to clean this up and get to the point of initial home screen - when all managers, views, singletones are stopped and nil’ed.

My current approach for tracking leaks was simple. In every meaningful classes I was counting instancesCount, a static variable which was incremented in init and reduced on deinitialization process. Of course, in XXI century with those all mature tools, its not smart idea for finding allocation leaks but... I don’t know why, Xcode instruments wasn’t very helpful. They were indicating troubles where everything was fine according to my approach. For example, instruments were saying that one of my manager is never deinitialized - which was not true, as instanceCount was 0 for this particular manager in the initial home screen. Weird.

Anyway, all this could close up with question: how to detect why my instance couldn’t be deinitialized and who keeps reference to it?

Reading code line by line and finding places of retain cycles is pointless as codebase is very complex and time - like always - is limited.


Solution

  • Use Instruments with Allocations Trace Template. It tracks reference count changes for each object and shows when it was increased and when it was decreased. No need for manual monitoring here.