- Retaining and Releasing
- Assigning to Instance Variables
- Automatic Reference Counting
- Returning Objects via Pointer Arguments
- Avoiding Retain Cycles
- Migrating to ARC
- Autorelease Pools
- Using Autoreleased Constructors
- Autoreleasing Objects in Accessors
- Supporting Automatic Garbage Collection
- Interoperating with C
- Understanding Object Destruction
- Using Weak References
- Allocating Scanned Memory
Automatic Reference Counting
With the release of iOS 5 and Mac OS X 10.7, Apple introduced Automatic Reference Counting (ARC). Conceptually, you can think of this as having the compiler automatically figure out when -retain and -release should be called, and calling them for you. The implementation is somewhat more complicated.
Rather than inserting message sends directly into the code, the compiler front end inserts calls to functions like objc_retain() and objc_release(). The optimizer then tries to combine or eliminate these calls. In the simple case, these functions do the equivalent of a message send. In some common cases, they are significantly more efficient.
In simple use, you can forget about memory management when using ARC. If you are using a recent version of XCode, then ARC is the default. If you are compiling on the command line or with some other build system, add -fobjc-arc. Now just forget about retaining and releasing objects.
It would be nice if life were that simple. Unfortunately, ARC does have some limitations. More specifically, it formalizes the fuzzy boundary between C memory and Objective-C objects. ARC divides pointers into three categories. Strong pointers follow the same retain/release semantics that we’ve looked at already. Weak pointers, which we’ll look at later, are non-owning references that are automatically zeroed when the object is destroyed. Unsafe unretained pointers are pointers that are ignored by ARC: You are responsible for tracking the lifetime of objects stored in them.
By default, all object pointers in instance variables or on the stack are strong. Object pointers in structures have no default. They must be explicitly marked with the __unsafe_unretained ownership qualifier. Even though this is the only permitted ownership for these pointers, it must be explicitly stated to provide a reminder to people reading the code that ARC will ignore it.