Wednesday, June 22, 2011

Memory Management in iPhone

In Mac OS X we have 2 options for memory management:
  • Reference Counting.
  • Garbage Collection(GC).
But, in iPhone there is no Garbage Collection(GC), it uses Reference Counting only.
Reference Counting also called as Retain Counting and Managed Memory.

Now, what is Reference Counting?

Each object keeps a count of how many other objects are using it (it is discussed in terms of Ownership).

If we create an object i.e. receive an object from a method that begins with alloc or new or contains the word copy, it means we own the object, and it reference count becomes 1.

If we receive an object from other method, we do not own the object. If we want to keep the object i.e. store it in an instance variable, we have to take ownership of that object by sending it a retain message, which increment it's retain count by 1.

We may also take ownership by copying the object  if it is capable of being copied, the object class must implement copyWithZone: .

If we own an object by any above method, we must relinquish our ownership by sending a release message to the object, which decreases its reference count by 1.

When an object's reference count becomes zero (0), the object is deallocated and its memory is returned to the heap.

If a release message causes an object's retain count to drop to zero(0), the release method  invokes the object's dealloc method.

Will be continue…...


  1. Really Really great work
    thanks alot.

    1. @tejpratap Malini thanks a lot, if you guys feels that this blog is really helpful for you then please join it.