3.1 · ARC, autorelease pools, object lifetime

Swift frees memory by counting references, not by hunting for garbage. Everything else in this topic, from cycles to side tables, follows from that one design decision.

Mental model. Every object has a count of how many strong references hold it. When the count reaches zero it dies, right then, on the thread that dropped the last reference.

How ARC works

Counting, deterministic death, and how it differs from a garbage collector.

  1. How does ARC work, and how is it different from garbage collection? 3.1.1 · L1
    ARC (automatic reference counting) is done by the compiler. It inserts retain and release calls around your code so that every class instance carries a count…
  2. What is a reference count, and how do you check that you hold the only reference? 3.1.2 · L2
    Each class instance has a small header holding its strong and unowned counts (and a flag for “has a weak side table”). Copying a strong reference adds one to…
  3. When exactly is an object deallocated: at the end of its scope, or after its last use? 3.1.3 · L3
    Neither is promised. The compiler is free to release an object after its last use, which can be earlier than the closing brace. Since Swift 5.7, lexical…

Manual counting and autorelease

The Objective-C heritage that still shapes Apple-platform memory.

  1. What did manual reference counting look like, and which rules did ARC automate? 3.1.4 · L2
    Before ARC, Objective-C programmers wrote the counting calls themselves: retain to take ownership, release to give it up, autorelease to hand something back…
  2. What is an autorelease pool, and when does a Swift loop need one? 3.1.5 · L2
    Autorelease means “release this later, not now”. Many Objective-C methods return autoreleased objects so the caller does not have to release them. Each such…

More in Memory, ARC & runtime