Reference Count in Objective-C’s Memory Management.


Q.35 What is Reference Count in Objective-C’s Memory Management.?Ans:-

  • This is Objective-C Memory technique which holds number of counts which is handling by Object. i.e one object is holding how many reference are count value.
  • When we are allocating the memory for any object then automatically reference count is incremented by 1. Ex. NSString *stringObject=[NSString alloc]init]; means you allocating the memory for stringObject. when we are releasing the memory then autometically reference count decrese by one (1).
  • Whenever one object reference count values is Zero(0) then it’s called object is free.
  • When we are using the “release” method then it will deallocate memory for the object and reference count also decrese by one (1).
  • When we are calling “retain” method then memory will deallocated for the object but reference count will not decrease.
  • When we are working with autoreleasepool object then always recommended to use “drain” method only because,”drain” method will call garbage collection system.
  • Garbage Collection is a automated process which will destroyed the application related memory when the application will terminated.
  • In place of creating object of type NSAutoreleasePool then always recommended to go for “@autoreleasepool” block.
    @ autoreleasepool
    {
    //code beniffiting from a local autoreleasepool
    }
  • In place of holding the reference count manually and deallocating by using “release” or “retain” it is recommended to go for ARC(Auto Reference Counting).
  • According to autorelease method whenever reference count value is zero then automatically object will be destroyed.
  • If we require to make enable ARC, then go for select Project File->Choose build setting and go to “APPLE LLVM Compiler 4.2- language” and choose Objective-C Auto Reference Count(ARC) YES or NO.

Kalavati Technologies Pvt Ltd