Memory management in iPhone

 Introduction

 Most of the object oriented languages have the Garbage Collector .  All the objects are allocated on the heap memory. The Garbage Collector is a thread that runs periodically to check all the objects, which are no more being referenced from the program. Garbage collector then de-allocates all these unreferenced objects on the Heap. In this environment programmer does not need to worry about de-allocating the objects explicitly.

In Objective – C we don't have garbage collector. ( Note: Its available from iOS 5.0 only). So in this environment we have to explicitly take care of allocation and deallocation of all the objects in our program.  And to manage it Objective C uses ‘reference counting' algorithm as the memory management algorithm. 

 Reference Counting: In this algorithm every object keeps track of it owners ( i.e. reference variables from the program ) . Number of owners is represented by the property retainCount declared in NSObject. If this retainCount goes to ‘0' the object gets deallocated automatically. We never call dealloc method on any object explicitly. retain method when called increases the retainCount by 1and release method when called decreases the retainCount by 1.

 Here I will explain one more concept of Autorelease pool, which is like a container that holds the autoreleased objects.

  • This pool is drained with every run-loop of the Application.
  • When the pool gets drained, autorelease pool sends a release message to all the objects it was holding.


Implement the following methods: retain, release, or autorelease

 -(id)retain {

NSIncrementExtraRefCount(self);

return self;
}

-(void)release {

if(NSDecrementExtraRefCountWasZero(self)) {
NSDeallocateObject(self);
}
}

-(id)autorelease {
// Add the object to the autorelease pool
[NSAutoreleasePool addObject:self];

return self;
}

Next Recommended Reading iPhone 5 coming in Sept with a boost