Junior — Middle
How does Automatic Reference Counting (ARC) work at runtime?
sobes.tech AI
Answer from AI
Automatic Reference Counting (ARC) is a memory management mechanism in iOS that automatically tracks the number of references to objects during program execution. When a reference to an object is created, the counter increases, and when the reference is removed, it decreases. When the counter reaches zero, the object is automatically deallocated from memory.
Example:
class Person {
var name: String
init(name: String) {
self.name = name
}
}
var person1: Person? = Person(name: "Ivan") // counter = 1
var person2 = person1 // counter = 2
person1 = nil // counter = 1
person2 = nil // counter = 0, object is deallocated
ARC helps prevent memory leaks without the need to manually manage memory allocation and deallocation.