Junior — Middle
Can you give an example of a situation where a weak reference is automatically nulled?
sobes.tech AI
Answer from AI
A weak reference is automatically set to null when the object it refers to is garbage collected (i.e., when there are no more strong references to it).
For example, in iOS, using a weak reference to a delegate:
class ViewController: UIViewController {
weak var delegate: SomeDelegate?
}
If the delegate object is destroyed (for example, goes out of scope and is deallocated), then delegate automatically becomes nil. This prevents access to an already released object and helps avoid memory leaks and errors.