Appendix C

Introduction to ARC

Automatic Reference Counting (ARC) is a feature of the new LLVM 3.0 compiler that does away with manual memory management of Objective-C objects. From a programmer’s perspective, enabling ARC in your project implies you do not need to call retain, release, or autorelease on your Objective-C objects. In fact, you will get a compile-time error if you attempt to do so. Instead, the compiler evaluates the lifetime of each object and inserts appropriate method calls for you. The compiler also generates appropriate dealloc methods for you.

It is important to keep in mind that ARC is not an addition to the Objective-C language. It is a compile-time feature. All ARC does is insert appropriate release and retain calls in your code where you would have. Another point worth mentioning is that ARC is not garbage collection. Garbage collection is an Objective-C language-level feature and is not supported on iOS.

In this appendix, you learn how to use ARC in your projects.

Object Ownership

To use ARC in your projects you need to move away from the retain-release model and think in terms of object ownership. This is best explained with an example. The following code allocates memory for and initializes an NSString object:

NSString* firstName = @"Andrew";

When the preceding statement is executed, the variable firstName points to the location in memory where the NSString instance is located, and effectively owns the contents of that memory location. In fact, firstName ...

Get iPhone and iPad App 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.