Junior — Middle
Kuidas toimub mälu vabastamine tsükliliste viidete objektide jaoks hallatud keskkondades?
sobes.tech AI
Vastus AI-lt
In managed environments like iOS with ARC (Automatic Reference Counting), memory deallocation for objects with cyclic references does not happen automatically, because ARC cannot break reference cycles.
To solve this problem, weak (weak) and unowned (unowned) references are used, which do not increase the reference count of the object. This allows breaking cycles and correctly freeing memory.
Example:
class Person {
var name: String
weak var apartment: Apartment? // weak reference
init(name: String) {
self.name = name
}
}
class Apartment {
let unit: String
unowned let tenant: Person // unowned reference
init(unit: String, tenant: Person) {
self.unit = unit
self.tenant = tenant
}
}
Here, Person and Apartment refer to each other, but one of the references is weak, preventing memory leaks.
If reference cycles are not broken, objects will remain in memory despite the absence of external references, leading to memory leaks.