Weak and unowned are common ways to avoid a reference cycle within your App.
Difficulty: Easy | Normal | Challenging
- Understand the concept of reference cycles
- Know what optionals are
Automatic Reference Counting (ARC): The system Swift uses to track and manage an App’s memory usage
Weak reference: A pointer to an object that doesn’t protect the pointer from being deallocated
Strong reference: A pointer to an object that protects the referred object from being deallocated by ARC
Unowned reference: A pointer to an object that protects the referred object from being deallocated by ARC, without incrementing the retain count of the object
Strong references (the default)
The default in iOS. However, we risk creating a retain cycle if an object holds a reference to its parent, and the parent holds a reference to the child.
This means that the reference count is increased by one.
A pointer to an object which is not protected from being deallocated. So the retain count is not increased.
When you access a weak reference, it is either a valid object or nil (that is, it is an optional).
Similar to weak references, but
- is not an optional so will never become nil
Can lead to a dangling pointer as it will never become nil during it’s lifetime. If the object being referred is deallocated, then the App will crash when the unowned reference is used.
Use a weak reference when the other instance has a shorter lifetime. Use an unowned reference when the other instance has the same lifetime or a longer lifetime.