Reference counting
Essence
Reference counting (retain count) is the mechanism memory management in Objective-C and Swift is built on. Every heap object has a count of strong owners:
- creating the object (
alloc/init,Class()) — count = 1; - a new strong owner (
retain, assignment to astrongvariable) — +1; - an owner lets go (
release, variable leaves scope) — −1; autorelease— "−1 later", when the autorelease pool drains;- the count hits 0 —
dealloc/deinitruns and the memory is freed.
Under MRC those calls were written by hand; under ARC the compiler inserts them, but the counters themselves exist and are incremented at run time (atomically).
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep