Sobes.tech
Junior — Middle

How is memory freed for objects with cyclic references in managed environments?

sobes.tech AI

Answer from AI

In managed environments such as iOS with ARC (Automatic Reference Counting), memory deallocation for objects with cyclic references does not happen automatically, as ARC cannot break reference cycles.

To solve this problem, weak and unowned references are used, which do not increase the reference count of the object. This allows breaking cycles and properly 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 leaks.

How is memory freed for objects with cyclic… - sobes.tech