Automatic Reference Counting

January 1st, 2012 Leave a comment Go to comments

We did a post a few months ago about the memory management issues in iOS. This post also relates to the same topic with respect to the new feature introduced in iOS 5 SDK. One of the new features in iOS 5 is Automatic Reference Counting (ARC). Before iOS 5, developers had to manually handle all memory management operations using retain, release or autorelease. You can still do that in iOS 5. But iOS 5 introduces ARC that greatly simplifies memory management for developers. If you enable ARC in your iOS app, you don’t need to use retain or release anymore. Instead the compiler itself takes care of tracking your objects and retaining or releasing them as required.

You must use Apple LLVM Compiler (Clang) to get the ARC feature in your application. Remember that you cannot enable ARC and also do retain/release/autorelease in your code by yourself.XCode 4.2 also provides a tool to help you migrate your existing code to make it ARC compliant. Simply select Edit -> Refactor… -> Convert to Objective-C ARC… and follow the instructions.

With ARC, you code will look like following:

Foo *foo = [[Foo alloc] init];

The compiler will see this code and automatically insert relevant release statement.

Foo *foo = [[Foo alloc] init];
obj_release(foo);		// added by compiler

Note that the compiler will use the C function to release the object rather than Objective C messaging, resulting in a small performance benefit.

If you use ARC, you don’t have to use retain/release/autorelease anymore. But that does not mean you can do away with dealloc method. Although not always required, you should still override dealloc method in your objects. The only change will be that your dealloc implementation will not contain any release statement.

- (void)dealloc {
	// no object release

The reason the dealloc method is still required is to free non retainable memory or external resources.

ARC also introduces three new ownership modifiers for properties in addition to existing assign, copy, and retain. The modifier weak creates a zeroing weak reference to an object which means that the reference will not be alive and will become nil when the referenced object is destroyed. The modifier strong will create a strong reference which guaranteed to be alive throughout the code. The modifier unsafe_retaineduses a weak relationship is but is non-zeroing and therefore dangerous to use.

ARC is a compile time feature included with the iOS 5 SDK. Therefore, it can be used with apps (existing or new) for any target iOS version, provided you use XCode 4.2 with iOS 5 SDK.

  1. No comments yet.

Leave a reply


six + = 9