Sobes.tech
Junior — Middle

Can you explain the mechanism of automatic memory management in ARC and how it frees unused objects?

sobes.tech AI

Answer from AI

ARC (Automatic Reference Counting) is a memory management mechanism in iOS that automatically tracks the number of references to objects and releases them when they are no longer needed.

How it works:

  • Each object has a reference count (retain count).
  • When a reference to an object is created, the count increases.
  • When a reference is removed, the count decreases.
  • When the count reaches zero, the object is automatically removed from memory.

ARC operates at compile time, inserting retain/release calls into the code, so programmers do not need to manually manage memory.

Example in Swift:

class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var person1: Person? = Person(name: "Ivan") // retain count = 1
var person2 = person1 // retain count = 2
person1 = nil // retain count = 1
person2 = nil // retain count = 0, Person object is deleted

Thus, ARC automatically frees objects when there are no more active references to them.