Junior — Middle
What is the main function of the automatic memory management mechanism ARC during program execution?
sobes.tech AI
Answer from AI
ARC (Automatic Reference Counting) is an automatic memory management mechanism in iOS that automatically tracks the number of references to objects during program execution and frees memory when the object is no longer in use.
The main function of ARC is to count strong references to an object and automatically invoke deallocation (dealloc) when the reference count reaches zero. This helps prevent memory leaks without the need to manually manage memory allocation and deallocation.
Example:
class Person {
var name: String
init(name: String) {
self.name = name
}
}
var person1: Person? = Person(name: "Ivan")
var person2 = person1 // reference count increases
person1 = nil // reference count decreases
person2 = nil // reference count becomes 0, object is deallocated