Junior — Middle
Is it possible to implement a mechanism that tracks objects using weak references without preventing their garbage collection?
sobes.tech AI
Answer from AI
Yes, in iOS (and in Swift) there is a mechanism of weak references, which allows tracking objects without retaining them in memory and preventing their deletion by the garbage collector (ARC).
A weak reference does not increase the reference count of an object, so when there are no strong references to the object, it is deallocated from memory.
Example of using a weak reference in Swift:
class Person {
let name: String
init(name: String) {
self.name = name
}
}
class Apartment {
weak var tenant: Person? // weak reference
}
var person: Person? = Person(name: "Ivan")
var apartment: Apartment? = Apartment()
apartment?.tenant = person
person = nil // the Person object will be removed, as there are no strong references
print(apartment?.tenant) // nil
Thus, weak references allow tracking objects without preventing their deletion.