Junior — Middle
In what cases is a weak reference used in programming?
sobes.tech AI
Answer from AI
Weak references are used when you need to refer to an object without preventing its garbage collection. This is useful to avoid memory leaks.
For example, in iOS, weak references are often used with delegates to prevent retain cycles. If object A references object B, and B references A back with a strong reference, they will not be deallocated.
An example of using a weak reference in Swift:
class ViewController: UIViewController {
weak var delegate: SomeDelegate?
}
Here, delegate is a weak reference, so if the delegate is deallocated, the reference automatically becomes nil, preventing a memory leak.