Sobes.tech
Junior — Middle

How can a cyclic reference be eliminated in memory management?

sobes.tech AI

Answer from AI

Cyclic references occur when two or more objects refer to each other, preventing the reference counting system from freeing memory because the reference count does not reach zero. In iOS, weak and unowned references are used to eliminate cyclic references.

  • weak — a reference that does not increase the reference count and is automatically set to nil when the object is deallocated.
  • unowned — a reference that does not increase the reference count but is not set to nil; used when you are sure the object will exist for a longer duration.

Example:

class Person {
    var apartment: Apartment?
}

class Apartment {
    weak var tenant: Person?  // weak reference to avoid cycle
}

let person = Person()
let apartment = Apartment()
person.apartment = apartment
apartment.tenant = person

Thus, weak references break the cycle, allowing ARC to properly free memory.

How can a cyclic reference be eliminated in memory… - sobes.tech