Reference Cycles and Weak References

suggest change

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 stay alive until the program terminates. That is a retain cycle.

Weak References

To avoid retain cycles, mark a reference weak or unowned. Neither increases the reference count. A weak reference becomes nil when the object is deallocated. An unowned reference does not become nil, and using it after deallocation traps.

class B { weak var a: A? = nil }

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents