Junior — Middle
Can you explain how weak references are implemented internally and how they work in memory?
sobes.tech AI
Answer from AI
Weak references in iOS (and generally in Objective-C/Swift) are references to objects that do not increase the reference count (retain count). This means that if there are no strong references to an object, it can be deallocated from memory even if weak references exist.
Internal implementation:
- A weak reference stores a pointer to the object but does not retain it in memory.
- When the object referenced by a weak reference is deallocated, the weak reference automatically becomes nil to avoid dangling pointers.
This works thanks to the ARC (Automatic Reference Counting) mechanism, which tracks strong references and notifies weak references when an object is deallocated.
Example of usage in Swift:
class Person {
var name: String
init(name: String) { self.name = name }
}
class Apartment {
weak var tenant: Person? // weak reference
}
var person: Person? = Person(name: "Alex")
var apartment = Apartment()
apartment.tenant = person
person = nil // Person object is deallocated, apartment.tenant automatically becomes nil