Automatic Reference Counting

Episode #9 | 10 minutes | published on 03/29/2012
Free Video
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 delegate;

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

// (ARC on iOS 5)
@property (nonatomic, weak) id 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
blog comments powered by Disqus
Back