Member-only story

Memory Management in Swift (iOS)

Mr.Javed Multani
2 min readOct 2, 2020

--

This topic outlines how and when the Swift runtime shall allocate memory for application data structures, and when that memory shall be reclaimed. By default, the memory backing class instances is managed through reference counting. The structures are always passed through copying.

Reference Cycles and Weak References

A reference cycle (or retain cycle) is so named because it indicates a cycle in the object graph:

Each arrow indicates one object retaining another (a strong reference). Unless the cycle is broken, the memory for these objects will never be freed.

A retain cycle is created when two instances of classes reference each other:

class A { var b: B? = nil }
class B { var a: A? = nil }let a = A()
let b = B()a.b = b // a retains b
b.a = a // b retains a -- a reference cycle

Both instances they will live on until the program terminates. This is a retain cycle.

Weak References

To avoid retain cycles, use the keyword weak or unowned when creating references to break retain cycles. class B { var a: A? = nil }

Weak or unowned references will not increase the reference count of an instance. These references don’t

contribute to retain cycles. The weak reference becomes nil when the object it references is deallocated.

a.b = b  // a retains b
b.a = a // b holds a weak reference to a -- not a reference cycle

When working with closures, you can also use weak and unowned in capture lists.

--

--

Mr.Javed Multani
Mr.Javed Multani

Written by Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer

No responses yet