Junior — Middle
Can you explain the main principles of ARC automatic memory management in iOS?
sobes.tech AI
Answer from AI
ARC (Automatic Reference Counting) is a memory management mechanism in iOS that automatically tracks and manages the lifetime of objects. The main principle of ARC is reference counting on objects.
When an object is created, ARC increases the reference count by 1. When the object is assigned to a new variable, the count increases; when a reference is removed, it decreases. When the reference count of an object 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") // reference count = 1
var person2 = person1 // reference count = 2
person1 = nil // reference count = 1
person2 = nil // reference count = 0, object is deallocated
It is important to avoid retain cycles, where two objects hold strong references to each other, preventing memory from being freed. To prevent this, weak and unowned references are used.