Junior — Middle
In what situations is a weak reference to an object used?
sobes.tech AI
Answer from AI
A weak reference in iOS is used to prevent strong reference cycles, which can lead to memory leaks. It does not increase the reference count of an object, so the object can be deallocated even if there are weak references to it.
Typical situations for using weak references:
- Delegates: often declared as
weakto avoid a cycle between the object and its delegate. - Closures: if a closure captures
self, to avoid a cycle,selfis captured with[weak self]. - Relationships between objects, where one object owns another, but the other should have a non-owning reference.
Example with a delegate:
protocol SomeDelegate: AnyObject {
func didUpdate()
}
class SomeClass {
weak var delegate: SomeDelegate?
}
Thus, a weak reference helps manage memory and prevent leaks.