O'Reilly logo

iOS 11 Programming Fundamentals with Swift by Matt Neuburg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 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, waiting 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. To put it another way, 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.

The specific events ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required