Junior — Middle
Kuidas vabastatakse mälu, mida objekt programmides kasutab?
sobes.tech AI
Vastus AI-lt
In iOS, memory release primarily occurs automatically thanks to the ARC (Automatic Reference Counting) system. Each object has a reference count, which increases when a new strong reference is created and decreases when it is removed. When the count reaches zero, the object is automatically destroyed and memory is freed.
If cyclic references occur in the code (for example, two objects with strong references to each other), memory is not released. To solve this problem, weak (weak) or unowned (unowned) references are used.
Example:
class Person {
var name: String
weak var apartment: Apartment? // weak reference to avoid cycle
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
}
}
Thus, memory is released automatically if references are managed correctly.