Sobes.tech
Junior

How does the Garbage Collector work in iOS?

sobes.tech AI

Answer from AI

Memory management system in iOS is based on Automatic Reference Counting (ARC), not on a traditional garbage collector. ARC automatically manages the lifecycle of objects by counting strong references to them. When the reference count of an object becomes zero, ARC deallocates the memory occupied by that object.

Key points:

  • Not a Garbage Collector: iOS does not use background garbage collectors that pause program execution to clean up memory.
  • ARC: The compiler inserts the necessary code to manage reference counts during compilation.
  • Strong references: Increase the reference count of an object, preventing its deallocation.
  • Weak references: Do not increase the reference count. They become nil when the object is deallocated. Used to prevent strong reference cycles.
  • Unowned references: Do not increase the reference count and do not become nil. Used when it is known that the reference will exist longer than the object it points to. Unsafe if the object might be deallocated before the reference is used.

Example of Strong, Weak, Unowned references:

class Person {
    let name: String
    var apartment: Apartment? // Strong reference to Apartment

    init(name: String) { self.name = name }
    deinit { print("\(name) is being deinitialized") }
}

class Apartment {
    let unit: String
    weak var tenant: Person? // Weak reference to Person

    init(unit: String) { self.unit = unit }
    deinit { print("Apartment \(unit) is being deinitialized") }
}

var john: Person?
var unit4A: Apartment?

john = Person(name: "John Appleseed")
unit4A = Apartment(unit: "4A")

john!.apartment = unit4A
unit4A!.tenant = john

In this example, apartment is a strong reference to Apartment, and tenant is a weak reference to Person to avoid strong reference cycles. Without weak, both objects would remain in memory even if john and unit4A become nil.