Episode #9

Automatic Reference Counting

10 minutes
Published on March 29, 2012
In this episode, I'll show you how to convert your project to use Automatic Reference Counting (or ARC) to eliminate the need to use retain, release, autorelease, and dealloc in your Objective-C code!

Caveats

One thing to note is that ARC is only partially supported on iOS 4.x. Specifically, weak references are not supported, so you have to use __unsafe_unretained to prevent retain cycles (similar to how you'd use assign for a parent/child relationship).

If you're on iOS 5, then you get the full power of and weak (which is a zeroing weak pointer).

Example:

// (Non-arc, weak delegate reference)
@property (nonatomic, assign) id<SomeProtocol> delegate;

// (ARC on iOS 4)
@property (nonatomic, __unsafe_unretained) id<SomeProtocol> delegate;

// (ARC on iOS 5)
@property (nonatomic, weak) id<SomeProtocol> delegate;

Combining ARC & non-ARC files

Click on your project, click on Build Phases, then expand Compile Sources. Once you've found the files that you need to modify, double click on the compiler flags field and enter:

  • -fobjc-arc if you want to enable ARC for these files in a project where ARC is not the default
  • -fno-objc-arc if you want to disable ARC for these files in a project where ARC is the default
Want more? Subscribers can view all 584 episodes. New episodes are released regularly.

Subscribe to get access →

Source Code

View on GitHub Download Source