Reference Cycle in Swift

Even some experienced developers make such mistakes

Cullen Sun
4 min readMar 14, 2023
Diagram by Author, reference cycle between two and more than two objects

Memory management for a developer is usually not trivial. Thanks to Automatic Reference Counting (ARC), memory management is made easy for iOS developers. It just works most of the time. However, the reference cycle is very tricky, and I have seen many experienced developers make such mistakes.

The official documentation mainly talks about the basic reference cycle between two objects A<->B. What I am going to show in this article is reference cycle among 3 or 4 objects, which is more difficult to spot.

The App with Memory Leak

The simple App for Demo by Author

The demo is a very simple iOS project with two screens. In the first screen “InitialViewController”, the user can click the button to launch the second screen “SampleViewController”, then the user can click the close button to dismiss the second screen. The second screen is coded using VIP clean architecture.

While the user enjoys using the App, memory is leaking behind. From the following screen from Xcode’s “Debug Memory Graph” feature, we can see that 5 instances of each of “SampleViewController”…

--

--

Cullen Sun
Cullen Sun

Written by Cullen Sun

Experienced software developer, and now learning AI and Robotics. Love reading.

No responses yet