How to Check ARC Counts and Prevent Retain Cycles in Swift
This should be fun
Memory management is important when writing Swift code.
One feature of Swift is Automatic Reference Counting (ARC) that tracks and manages an app’s memory usage. Although ARC does most of the heavy lifting, it is important to understand how memory leaks occur and and how we can use ARC to prevent them.
To help this explanation along I’ve created a simple example with just two view controllers using the storyboard.
How ARC Works
Every time you create an instance of a reference type, ARC stores information about the instance. As part of this information ARC has a counter to make sure that when no references exist to the object it is released freeing memory.
So when we reference an instance we generally make a **strong** reference to the instance, and it will not be deallocated for as long as a strong reference remains.
We can use **weak** references to refer to an instance without keeping a strong hold. This avoids creating a strong reference cycle, but does not stop ARC from disposing of the referenced instance.
Similarly **unowned** references are used when the other instance (not that held) has an equal or longer lifetime than…