6.3 · The run loop, its modes, and the main-thread contract

Everything on screen happens because a loop on the main thread woke up, handled something, and went back to sleep. Knowing how that loop works explains frozen timers, stuck UI and odd ordering.

Mental model. A run loop is “sleep until something happens, handle it, repeat”. Timers, touches, display updates and the main queue are all things it wakes up for.

How the loop runs

Sources, timers, observers, and one trip around the loop.

  1. What is a run loop, and what happens in one iteration? 6.3.1 · L2
    A run loop is an event loop attached to a thread. Its job: block cheaply until there is work, process it, block again. Inside it, work comes from sources…
  2. What are run loop modes, and why does a Timer stop firing while the user scrolls? 6.3.2 · L3
    A run loop runs in one mode at a time, and each mode has its own set of sources, timers and observers; only the ones registered for the current mode fire. The…

The main thread

What it must do, and what must stay off it.

  1. What is the main-thread contract, and why does DispatchQueue.main.sync from the main thread crash? 6.3.3 · L2
    UIKit and most of SwiftUI’s view layer are main-thread only: you create and update views, touch layout and read many properties on the main thread. This is…

More in iOS platform internals