Saturday 21 September 2013

Memory management in Objective C

Hi all, today we will discuss about memory management in Objective C. Its an important concept in Objective C. Lets see how it works. Memory is very important for every application. Especially for mobile applications. So, its important to manage memory in our applications.

Thumb rule in Objective C memory management is, who ever creates an object or gets ownership of an object, they are responsible to release that particular object. We discusses in my earlier in my posts that Objective C is object oriented programming language. So, there will be object sharing. To manage this, we have retain count mechanism in Objective C. Retain count represents number of owners to a particular object.

Lets say we have created an object in class A following way :

Object *obj = [[Object alloc] init]; // retain count is 1.

Now, what to do if the same object is shared by another class B? Class B has to get owner ship of obj. Otherwise, if we use obj in class B after it is released by class A, application will be crashed as there are no owners to obj.

Lets retain obj in class B :

[obj retain]; // retain count is 2.

Will increase retain count by 1. Thus indicates class B is also owner of obj. Its responsibility of class B to release obj. Whenever send release message on obj, its retain count will be decremented by 1.

[obj release]; // retain count is 0


Now, retain count of the object obj is 1. After some processing, lets say I am done with using object obj in class A also. I need to release memory related to this object. What I need to do is, just send "release" message on this object.

[obj release];  // retain count 0.

Now, retain count of the obj is 0. There are no owners present for this object. Objective C runtime environment will take care of reclaiming memory allocated to obj.

Following summary explains how memory is managed :


         Class A                     Class B                       Class A                                Class B
           alloc                          retain                         release                                 release
obj (retain count 1)     obj (retain count 2)         obj (retain count 1)          obj (retain count 0)


In our next tutorial we will discuss about autorelease pools and setter methods using memory management.

Please feel free to post your questions.