Chapter 11. Cocoa Events

All of your app’s executable code lies in its functions. The impetus for a function being called must come from somewhere. One of your functions may call another, but who will call the first function in the first place? How, ultimately, will any of your code ever run?

After your app has completely finished launching, none of your code runs. UIApplicationMain (see “How an App Gets Going”) just sits and loops — the event loop — waiting for something to happen. In general, the user needs to do something, such as touching the screen, or switching away from your app. When something does happen, the runtime detects it and informs your app, and Cocoa can call your code.

But Cocoa can call your code only if your code is there to be called. Your code is like a panel of buttons, ready for Cocoa to press one. If something happens that Cocoa feels your code needs to know about and respond to, it presses the right button — if the right button is there. Cocoa wants to send your code a message, but your code must have ears to hear.

The art of Cocoa programming lies in knowing what messages Cocoa would like to send your app. You organize your code, right from the start, with those messages in mind. Cocoa makes certain promises about how and when it will dispatch messages to your code. These are Cocoa’s events. Your job is to know what those events are and how they will arrive; armed with that knowledge, you can arrange for your code to respond to them.

Reasons for Events ...

Get iOS 14 Programming Fundamentals with Swift now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.