Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 38 ยท Memory Management and ARC

Automatic Reference Counting (ARC)

Learn how ARC inserts retain and release for you, which rules it follows, what it forbids, how to migrate from manual counting, and how to reason about object lifetime in modern Objective-C.

Manual reference counting works, but it asks humans to do something a compiler is better at: counting. Automatic Reference Counting (ARC) is a compile-time feature of Clang. The compiler reads your code, applies the ownership rules you already know, and inserts the retain, release and autorelease calls itself. There is no runtime collector, no pause, and no change to how objects are laid out. The result is the same machine code you would have written by hand, minus the mistakes.

ARC is the default for every new Objective-C project. Understanding what it does (and where it needs your help) is the difference between code that "just works" and code that leaks through a cycle.

What ARC does for you

You write:

OBJECTIVEC
- (void)showGreeting {
    NSString *name = [[NSString alloc] initWithFormat:@"User %d", 42];
    NSLog(@"Hello, %@", name);
}

The compiler produces the equivalent of:

OBJECTIVEC
- (void)showGreeting {
    NSString *name = [[NSString alloc] initWithFormat:@"User %d", 42];
    NSLog(@"Hello, %@", name);
    [name release];   // inserted by ARC at the end of the scope
}

For local variables, ARC releases the object when the variable goes out of scope (or earlier, once it is no longer used). For instance variables and properties, it generates the retain/release pairs in setters and releases the contents in dealloc. For return values it follows the naming rules: a method called newThing returns an owned object; thing returns one that is autoreleased or otherwise safe.

Retain and release as a picture

ARC in four steps

You write code No retain or release
Clang analyses Ownership of each pointer
Inserts calls retain, release, autorelease
Runtime counts Frees at zero

All of this happens at compile time.

1 / 2

What ARC forbids

Because the compiler is in charge, some manual calls become compile errors:

  • You cannot call retain, release, autorelease or retainCount.
  • You cannot call [super dealloc]. You may still override dealloc to clean up non-memory resources (observers, file descriptors, free() calls on C buffers), but you do not release the instance variables.
  • You cannot store an Objective-C object pointer in a C struct or union under ARC, because the compiler cannot track ownership inside it.
  • You cannot cast freely between id and void *. You need an explicit bridge (see below).

Ownership qualifiers

Variables of object type carry an ownership qualifier. The default for locals is __strong.

Qualifier Meaning
__strong Owns the object (default). Retains on assignment, releases on overwrite.
__weak Does not own it. Becomes nil automatically when the object is destroyed.
__unsafe_unretained Does not own it, and does not become nil (dangling pointer risk).
__autoreleasing Used for out-parameters such as NSError **.
OBJECTIVEC
__strong NSString *owner = @"kept alive";
__weak   NSString *peek  = owner;       // zeroing weak reference
owner = nil;                            // peek is now nil if the string was freed

(String literals are immortal, so peek would not actually become nil here. With a heap object the principle holds.)

Simulating ARC's insertion in C

Here is a stand-in where the "compiler" is a pair of macros. SCOPE_OBJECT declares an owned object and a cleanup attribute releases it automatically at the end of the block, which is conceptually what ARC does at the end of a scope. This uses a GCC/Clang extension, so it also demonstrates that ARC's trick is available at the C level.

C Stand-in: automatic release at end of scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The local temp disappears at the closing brace. shared survives because another owner retained it. That is the same outcome ARC produces for Objective-C locals.

Bridging with Core Foundation

Core Foundation objects (CFStringRef, CFArrayRef) are C types that ARC does not manage. When you convert between them and Foundation objects you tell the compiler who owns the result:

OBJECTIVEC
// No ownership change: the CF object is still managed manually
NSString *s = (__bridge NSString *)cfString;

// Transfer: ARC takes over ownership, you will NOT call CFRelease
NSString *t = (__bridge_transfer NSString *)CFStringCreateCopy(NULL, cfString);

// Retained: you get a CF object that you must CFRelease yourself
CFStringRef c = (__bridge_retained CFStringRef)someNSString;
CFRelease(c);

Rule of thumb: __bridge_transfer moves a CF object into ARC; __bridge_retained moves an ARC object out to manual management.

Returning objects and autorelease

When a method returns an object it created, it cannot release it before returning. ARC therefore uses autorelease (or an optimized equivalent called return-value optimization) so the caller can take ownership if it wants to. You never write this. You only follow the naming conventions: a method named newFoo, allocFoo or copyFoo hands over an owned object; anything else is fine to use temporarily and strong properties keep what they need.

Migration notes

Old code that uses retain/release can be converted with Xcode's ARC migration tool, or compiled per file with -fno-objc-arc. Libraries often keep both modes side by side. Convert gradually, one file at a time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does ARC insert retain and release calls?

    ARC is a compiler feature; the generated code is ordinary retain and release.
  2. 2. Which call is a compile error under ARC?

    retain, release, autorelease and retainCount are unavailable when ARC is on.
  3. 3. What does a __weak variable do when its object is deallocated?

    Zeroing weak references are set to nil automatically; __unsafe_unretained ones are not.
  4. 4. What does __bridge_transfer do?

    After a transfer, ARC owns the object, so you must not call CFRelease.

Summary

  • ARC inserts retain, release and autorelease at compile time using the ownership rules you already know.
  • Manual memory calls are errors; dealloc is only for non-memory cleanup.
  • Qualifiers __strong, __weak, __unsafe_unretained and __autoreleasing describe ownership.
  • ARC does not manage C memory or Core Foundation objects, and it cannot break cycles.

Next: Strong and Weak References