Tuesday, July 20, 2010

Java reference, Objective-C retain count

Java

How Java's garbage collector knows that an object must be destroyed? An object is a candidate for garbage collector if they lose all its references. For example Object B below. It is referred by variable B1 and B2. Once both B1 and B2 lose reference to it, none knows that it exists, then it becomes candidate for garbage collector.



Objective-C

Objective-C on the other hand, uses different approach. Each object holds a variable named retainCount. It is set to 1 the first time the object created. It is incremented anytime the object retained or copied. It is decremented anytime it is released. When the retainCount equals zero, the object is destroyed.

Those differences happen because they use different approach in memory management. Java depends on its garbage collection algorithm to release unused memory, while Objective-C gives programmers more responsibility to release their objects. If you allocate memory, it is your responsibility to release it.

However, since XCode 4.2 Apple has put new feature called ARC (Automatic Reference Counting) to ease developers’ job dealing with allocating and releasing memory. It is sort of AOP implementation in Objective-C for me.

Using ARC, we don’t need to release memory we allocated before, in other words we don’t need to deal with retain-release code anymore. The compiler takes care the code of retaining-relasing objects. At compile time, the compiler crosscuts your code and adds some line of retain-release code. Using ARC we now only have to deal with our logic.

0 comments:

 

©2009 Stay the Same | by TNB