Skip to the workspace
Pebellslearn by building
Core Programming Concepts  ›  Lesson

Memory Management with ARC

Memory Management 12 minARC frees a class instance when its strong reference count reaches zero, so strong reference cycles must be broken with weak or unowned references.

ios / Memory Management with ARC

Explore each scene at your own pace.

01 · The rule

The rule

Memory Management with ARC

TrailLog's hike detail screen closes, but its memory never comes back. Open and close it twenty times and the app is using far more memory than it should. Nothing crashed; objects simply never got freed. Understanding how iOS frees memory explains why.

The rule

ARC frees an object when its last strong reference disappears.

Swift uses Automatic Reference Counting (ARC) for class instances. Every strong reference to an object adds one to its count; when a reference goes away, the count drops. At zero, the object is destroyed and deinit runs. No garbage collector pauses the app; the counting happens as your code runs.

ARC applies to classes (and closures). Structs and enums are values and are simply copied, so they are not counted.

The problem is a retain cycle: two objects holding strong references to each other. Neither count ever reaches zero, so both leak.

class HikeDetailViewController: UIViewController {
    var onSave: (() -> Void)?
    var hike: Hike?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Leak: the controller owns the closure, and the closure owns the controller.
        onSave = { self.showSavedBanner() }
    }
}

The fix is to make one side weak or unowned:

onSave = { [weak self] in
    self?.showSavedBanner()
}
  • weak — does not add to the count. It must be an optional var, and becomes nil automatically when the object is destroyed. Safe default.
  • unowned — also does not add to the count, but is not optional. Use it only when the other object is guaranteed to outlive this reference; otherwise accessing it crashes.

The classic places cycles hide: closures stored as properties that mention self, and delegates, which is why delegate properties are almost always declared weak var delegate.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.