Thursday, October 3, 2013

Memory Management in Objective C

In this topic, we will discuss Reference Counting and some other memory management topics related to Objective C.

Reference Counting

Reference Counting is a technique of storing a number of reference to an Object at any given state. As soon as the reference count goes to the Zero object is released from the memory. It is important from the development point of view of application where memory is critical and to maintain responsiveness. It is the most simple algorithm for memory management. 

Objective C provides two methods of Memory Management

  1. MRR - Manual Retain-Release: In this method, you explicitly keep track of the Objects you own. 
  2. ARC - Automatic Reference Counting uses the same algorithm of MRR, However, while using ARC Compiler insert appropriate statements in your code at compile time. 
With MRR the crash of application because of memory related issues was increasing. Even with the help of many tools and support from the Xcode the issues remains. A Developer has to stick to the rules of allocating and deallocating the objects. 

What ARC does, it automates those rules and that is what compilers are best at. But it still compatible with MRR. ARC is not a new Model. Now the compiler adds retain/release/autorelease for you. 

How do you turn ARC ON
New projects are defaults to ARC.
Existing projects need to migrate to ARC. Here the detail Transition to ARC release notes.

Rules of ARC
  • No Access to memory methods.
  • No Object Pointers in C Structs.
  • No casual casting from id <--> void*
  • No NSAutoreleasePool
How Reference Counting Memory Management is different from the Garbage Collection?
Garbage Collector collects the objects which can be cleaned from the memory as they are not being referenced by any other object. It is not certain when the garbage collector will start sweeping the objects, unlike Reference counting which deallocates the object as soon as the object reference count reaches 0.

Learn more
Refer to this article on Wikipedia for more Reference_counting details.
You can refer to the Apple Dev Library for more details.
Here are WWDC 2012 presentation slides for ARC.

No comments:

Post a Comment