Junior — Middle
Kas saaksite selgitada automaatse mälu halduse ARC tööpõhimõtet Objective-C-s?
sobes.tech AI
Vastus AI-lt
ARC (Automatic Reference Counting) is a memory management mechanism in Objective-C that automatically tracks the number of references to objects and frees memory when the object is no longer in use.
The working principle of ARC is based on reference counting (retain count):
- When an object is created, its reference count is 1.
- When the object is assigned to a new variable, the count increases (retain).
- When a variable goes out of scope or is assigned nil, the count decreases (release).
- When the count reaches 0, the object is automatically removed from memory.
Example:
NSObject *obj = [[NSObject alloc] init]; // retain count = 1
self.property = obj; // count increases
obj = nil; // count decreases
// When all references to the object disappear, memory is automatically freed
Developers do not need to explicitly call retain/release; ARC inserts these calls during compilation, reducing the likelihood of memory management errors such as leaks or double releases.