Can you explain what is meant by the term MRC and what is its essence?
sobes.tech AI
Answer from AI
MRC (Manual Reference Counting) is a memory management mechanism where the programmer is responsible for counting references to an object and freeing memory when the object is no longer needed.
In iOS and Objective-C, before the advent of ARC (Automatic Reference Counting), developers manually increased and decreased the reference count using retain and release methods. When the reference count of an object reaches zero, the memory for the object is released.
The essence of MRC:
- Every time you keep a reference to an object, call
retain. - When the reference is no longer needed, call
release. - If the reference count reaches zero, the object is destroyed.
This requires careful attention to avoid memory leaks (forgetting to call release) or access errors to already freed memory (calling release too early).
Example:
NSObject *obj = [[NSObject alloc] init]; // reference count = 1
[obj retain]; // reference count = 2
[obj release]; // reference count = 1
[obj release]; // reference count = 0, object is released
MRC requires the developer to strictly control the object lifecycle, unlike ARC, where this process is automated.