skip to content

In Objective-C, what do retain, release and autorelease do under manual reference counting, and what does ARC change about them?

level: middleimportance: should knowfreq 55%

answer

  1. ownership follows the method name
  2. alloc, new, copy, mutableCopy
  3. a deferred release at pool drain
  4. the compiler inserts the calls
  5. -fno-objc-arc on one file

basics

~20 s

Under manual reference counting, retain takes ownership, release gives it up, and autorelease gives it up later, when the enclosing autorelease pool drains. ARC makes the compiler insert those calls from the same ownership rules and forbids writing them yourself.

solid answer

~40 s

Manual reference counting runs on four rules from Apple's memory-management guide: you own what you create with a method whose name begins with `alloc`, `new`, `copy` or `mutableCopy`; you can take ownership with `retain`; you must give up what you own with `release` or `autorelease`; and you must not release what you do not own. `autorelease` is a deferred `release`, used to return an object without freeing it first; the release happens when the enclosing `@autoreleasepool` block ends. ARC, available from Xcode 4.2, applies the same rules at compile time: it inserts retains and releases, generates `dealloc` chaining, and makes explicit `retain`, `release`, `autorelease`, `retainCount` and `[super dealloc]` errors. Autorelease pools remain, so a loop that creates many temporary objects can still need its own `@autoreleasepool`.

code

objective-c · 26 lines
objective-c
// Compiled with -fno-objc-arc: manual retain and release.
#import <Foundation/Foundation.h>

@interface PPPrintOrder : NSObject {
    NSString *_title;
}
- (void)setTitle:(NSString *)title;
- (NSString *)summary;
@end

@implementation PPPrintOrder
- (void)setTitle:(NSString *)title {
    if (title != _title) {
        [_title release];        // give up the old value we owned
        _title = [title copy];   // copy: we own the new one
    }
}
- (NSString *)summary {
    NSString *s = [[NSString alloc] initWithFormat:@"Order: %@", _title];
    return [s autorelease];      // owned by alloc, released at pool drain
}
- (void)dealloc {
    [_title release];
    [super dealloc];
}
@end

go deeper

for a junior

Recall the four ownership rules and which method-name prefixes return an object you own.

for a middle

Explain autorelease as a deferred release, when a pool drains, the three cases for your own pool, and what ARC forbids.

for a senior

Diagnose over-releases and leaks in manual files, a loop that spikes memory, and a background thread without a pool; know the per-file -fno-objc-arc setting.

for a principal

Decide whether remaining manual-counting files are converted to ARC or fenced, weighing migration risk against the bugs only manual counting can produce.

## Ownership is the whole model Objective-C objects are **reference counted**: an object stays alive while it has at least one owner and is destroyed when the last owner gives it up. Apple's *Memory Management Policy* states four rules: 1. **You own any object you create** with a method whose name begins with `alloc`, `new`, `copy` or `mutableCopy`. 2. **You can take ownership** of an object with `retain`, typically in a setter or an initializer that stores it. 3. **You must relinquish ownership** of an object you own, by sending `release` or `autorelease`. 4. **You must not relinquish** ownership of an object you do not own. The naming rule matters: `[NSString stringWithFormat:...]` returns an object you do not own, while `[[NSString alloc] initWithFormat:...]` returns one you do. ## The three messages | Message | Effect | Typical use | |---|---|---| | `retain` | adds an owner | storing a value in an ivar | | `release` | removes an owner now | done with an object you own | | `autorelease` | removes an owner when the pool drains | returning an object you created | A method that builds a string with `alloc` and returns it cannot `release` it first, or the caller would receive a freed object; returning it without any release would leak, because the method name does not tell the caller it owns the result. `autorelease` solves this: ownership is given up, but the actual `release` waits until the end of the current autorelease pool block. ## Autorelease pools An `@autoreleasepool { ... }` block marks a pool. At its end, every object autoreleased inside it receives one `release` per `autorelease` it was sent. Pools nest, and each thread keeps its own stack of them. UIKit wraps each event-loop iteration, such as a tap, in a pool, so most code never writes one. Apple names three cases where you do: - a program not built on a UI framework, such as a command-line tool; - a **loop that creates many temporary objects**, where a pool inside the loop body releases each iteration's temporaries before the next one, lowering peak memory; - a **secondary thread** you start yourself that makes Cocoa calls, which must create a pool as soon as it begins or it leaks autoreleased objects. Treat anything autoreleased inside a pool as disposed of after the block ends: do not return it or message it unless you retained it inside the block. ## What ARC changes **Automatic Reference Counting** keeps the same model and moves the bookkeeping into the compiler. Apple's transition notes list the changes: - The compiler inserts `retain`, `release` and `autorelease` where the ownership rules call for them, and generates the release of instance variables in `dealloc`. - You cannot call or implement `retain`, `release`, `retainCount` or `autorelease`, and you cannot call `dealloc`; clang reports "ARC forbids explicit message send of 'release'". - A custom `dealloc` is still allowed for other resources but must not call `[super dealloc]`; the compiler chains it. - `NSAutoreleasePool` is unavailable; the `@autoreleasepool` block replaces it and works under manual reference counting too. - Ownership becomes part of variable declarations: `__strong` (the default), `__weak`, `__unsafe_unretained` and `__autoreleasing`. ARC is not a tracing garbage collector: there is no collector thread and no pause, and a retain cycle still leaks. ARC also does not manage memory from `malloc` or Core Foundation objects, which still need explicit release. ## How the mistakes show up Manual counting fails in two directions, and both are hard to trace: - **Over-release.** One `release` too many frees the object while someone still points at it. The crash often comes later, for example when an autorelease pool drains and sends its own `release`, far from the line that released wrongly. - **Leak.** A missing `release`, or a returned object the caller does not know it owns, keeps memory alive for the life of the app. - **Wrong naming.** A method that returns an owned object without an owning prefix, or the reverse, misleads every caller, manual or ARC. ## Mixing the two in one target Apple's notes date ARC to Xcode 4.2, deploying to iOS 4 and later, with weak references needing iOS 5. Old code often still has manual files. ARC is set per file: the target compiles with `-fobjc-arc`, and individual files can be marked `-fno-objc-arc` in the target's Compile Sources build phase. The two kinds of file interoperate because both follow the same naming conventions, which is why those conventions stay important under ARC: a method named `newPreview` tells ARC callers they receive an owned object, and ARC forbids an accessor whose name begins with `new` unless you give it another getter name.

  • Why must manual reference counting code not release the string returned by stringWithFormat:?
    Its name does not begin with `alloc`, `new`, `copy` or `mutableCopy`, so the caller does not own it; the factory has already autoreleased it. Releasing it gives up ownership the caller never had, and when the pool later sends its own `release`, the object is over-released and the app crashes. Retain it if you need to keep it.
  • What still belongs in a dealloc method under ARC?
    Anything ARC does not manage: Core Foundation objects, memory from `malloc`, file descriptors, and unregistering from things that hold a pointer to you, such as key-value observing. You never release object instance variables there and never call `[super dealloc]`; the compiler generates both.
  • Why does a thread you create yourself need its own @autoreleasepool?
    Each thread keeps its own stack of autorelease pools, and the main thread's event-loop pools do not cover it. If the thread makes Cocoa calls and has no pool at the top of its work, autoreleased objects created there are never released and the app leaks, so Apple's guide says to create one as soon as the thread starts.

autorelease is like dropping a library book in the returns bin instead of handing it to the librarian: you have given it up, but it is only checked in when the bin is emptied. A long loop that keeps dropping books overfills the bin, so you empty it more often with an inner pool.

  • ARC is a garbage collector that runs in the background.
  • Under manual counting you release every object you use, including stringWithFormat: results.
  • ARC removed autorelease, so @autoreleasepool is only for manual code.
  • An object autoreleased inside a pool block can safely be returned after it.
  • Mixing manual and ARC files requires converting the whole target at once.
  • ARC makes retain cycles impossible.