Junior — Middle
Can you explain the concept of Release in Objective-C and its role in memory management?
sobes.tech AI
Answer from AI
In Objective-C, the release method is used for managing the lifetime of objects under reference counting. Each object has a reference count, which increases with retain and decreases with release. When the count reaches zero, the object is destroyed and memory is freed.
The role of release is to decrement the reference count, signaling that the current owner no longer needs the object. This helps prevent memory leaks by freeing resources when they are no longer needed.
Example:
NSObject *obj = [[NSObject alloc] init]; // ref count = 1
[obj retain]; // ref count = 2
[obj release]; // ref count = 1
[obj release]; // ref count = 0, object is destroyed
It is important to call release as many times as retain or alloc/init were called to balance the reference count and avoid leaks or premature deletion.