Its goal is to free the memory of objects that are no longer accessible from your code.
For instance in Java :
String str = "my string"; str="my other string";
- The first line create an object String and assign it to the label str.
- The second line create another String object and assign it to the label str.
Since str is mapped to the second String object. The first one is no longer reachable from your code because you don’t have to access it.
The garbabe collector will go through all the objects in memory and look at the reference counter. if it’s at zero, the object is deleted.
This is a very convenient way to manage the memory because the developer don’t have to think about it.
But the garbage collector is also a little bit heavy since it have to go through all your objects to find the ones which can be deleted.
On a PC that works perfectly because there is enough memory to run the garbage collector regularly and there is enough power to run it without slowing down the app.
On a mobile device like the iPhone or the iPad, the quantity of memory is lower than on a PC and the processor is not as fast.
That’s why there is no gabarge collector on iOS.
How to manage the memory ?
Instead of having a garbage collector that clean your memory, you will have do it manually. That’s is done by changing the value of the counter of references.
[myObject alloc]+1 [myObject retain]+1 [myObject release]-1
alloc and retain will increment the counter of references, release decrement it.
When the counter is at zero, the object is deleted.
Each thread have also an autorelease pool. Each object of this pool will be released with the pool, usually at the end of the thread’s life.
For instance the code
NSString* str= @"my str";
create a NSString object an put it in the autorelease pool of the thread. You don’t have to worry about this object anymore.
An easy rule is to have : count(alloc)+count(retain)=count(release)+count(autorelease)
Autorelease is easy to use since you don’t have to worry about when to release an object, but objects in this pool are kept in memory until the pool is released, which can occur in a long time.
A bad memory management will result in memory leaks that can crash your app. Lukely Xcode provide a tool to find leaks called instrument.