What is a RunLoop Anyway? Swift and iOS Guide

Threads are not all that there is to getting stuff done.

Steven Curtis

--

Photo by Ross Stone on Unsplash

Apple Say

Apple has enabled the iOS SDK to handle user events and trigger responses within the application through use of the event queue.

Eh?

A run loop keeps your thread busy when there is work to do and put your thread to sleep when there is none.

In other languages a run loop might be called an event loop.

A Simple Example

Let’s take an example about how views are laid out.

When a user interacts with an application, the event is added to the event queue, which can then be handled by the application and potentially dispatched to other objects in the application. Once the events are handled, they then return control to the main run loop and begin the update cycle, which is responsible for laying out and drawing views.

Then

Once control is returned to the main run loop, the system renders layout according to constraints on view instances.

When a view is marked as requiring a change in the next update cycle, the system executes all the changes.

The system works through the run loop, then constraints before the deferred layout pass.

A better explanation

Apps are interactive. That is, they react to user input and then move back to a state where they can accept user input.

In the example above we are seeing how the run loop can be used to update views on the screen.

In fact, the run loop is responsible for

  • Touch events, and selector events
  • Timer events
  • Drawing points on the screen

So a runloop checks for events, and keeps checking.

Runloops and threads

--

--