Sobes.tech
Junior

How does the garbage collector work?

sobes.tech AI

Answer from AI

In the context of iOS/macOS development, Swift/Objective-C uses Automatic Reference Counting (ARC) rather than a garbage collector (GC).

ARC automatically manages memory by counting the number of strong references to each class instance (and captures in closures). When the strong reference count drops to zero, the system frees the memory occupied by the object.

Key points of ARC:

  • Strong references: Increase the reference count. The object remains in memory as long as there is at least one strong reference.
  • Weak references: Do not increase the reference count. Used to prevent strong reference cycles. They are optional and become nil when the object is deallocated.
  • Unowned references: Do not increase the reference count. Used when the lifecycle of the referenced object is known and one object will always exist as long as the other. The reference is non-optional. Accessing an unowned reference after the object has been deallocated will cause a runtime error.

ARC works at compile time, inserting retain (to increase the count) and release (to decrease the count) calls in the appropriate places.

class MyClass {  
    var prop: String = ""  
}

var reference1: MyClass? = MyClass() // Reference count = 1
var reference2 = reference1 // Reference count = 2

reference1 = nil // Reference count = 1
reference2 = nil // Reference count = 0, object is deallocated
class Person {  
    let name: String
    weak var apartment: Apartment? // Weak reference to avoid cycle
    init(name: String) { self.name = name; print("
\(name) is being initialized") }
    deinit { print("
\(name) is being deinitialized") }
}

class Apartment {  
    let unit: String
    unowned var tenant: Person // Unowned reference
    init(unit: String, tenant: Person) { self.unit = unit; self.tenant = tenant; print("Apartment \(unit) is being initialized") }
    deinit { print("Apartment \(unit) is being deinitialized") }
}
How does the garbage collector work? — iOS - sobes.tech