這系列搭配 iOS 深入學習的進度一起讀英文文件,本篇選的是 Apple 關於主事件循環的說明。(特此聲明:從這篇起,集數與 iOS 學習系列同步,方便一起對照。若有錯誤之處請不吝指正,互相學習,感謝!)→ 以下用繁體中文書寫。
In the main event loop, an application continuously routes incoming events to objects for handling and, as a result of that handling, updates its appearance and state. An event loop is simply a run loop: an event-processing loop for scheduling work and coordinating the receipt of events from various input sources attached to the run loop. Every thread has access to a run loop. In all but the main thread, the run loop must be configured and run manually by your code. In Cocoa applications, the run loop for the main thread—the main event loop—is run automatically by the application object. What distinguishes the main event loop is that its primary input source receives events from the operating system that are generated by user actions—for example, tapping a view or entering text using a keyboard.
主事件循環的工作是:持續把送進來的事件路由給各個物件處理,而處理的結果又會反映到 App 的外觀與狀態上。所謂事件循環,本質上就是一個 run loop——一個負責排程工作、統籌來自各輸入源事件的迴圈。每個執行緒都有自己的 run loop,但除了主執行緒之外,其餘的都必須由你的程式碼手動建立與啟動;而在 Cocoa 應用中,主執行緒的 run loop 由應用程式物件自動驅動。主事件循環的特殊之處在於,它的主要輸入源接收的是作業系統產生的、來自使用者操作的 event,例如點擊視圖或用鍵盤輸入文字。
原文接著說明:App 啟動後不久,就會建立主事件循環所需的基礎設施,與負責送達低階使用者事件的系统元件建立連線。這些事件透過安裝在主執行緒 run loop 中的輸入源抵達。由於每個事件都必須個別、依抵達順序處理,因此低階事件被放進一個先進先出的佇列。一旦初始使用者介面出現在螢幕上,App 此後便由外部事件驅動:應用程式物件取出佇列中最上面的物件,轉成事件物件(iOS 上是 UIEvent,OS X 上是 NSEvent),再分派給其他物件處理。分派的呼叫返回後,再取下一個,如此循環直到 App 結束。
啟動時同時建立的還有一組核心物件,負責繪製介面與處理事件,包含視窗與各類視圖。應用程式物件取得事件後,會分派給事件發生的那個視窗;視窗再轉給最適當的處理者:多點觸控與滑鼠事件交給手指或游標下面的那個 view;鍵盤、動作等其他事件則交給 first responder。若這個初始 view 不處理,事件會沿著 responder chain 往上傳遞,直到被處理或被丟棄。處理過程中,view 常會啟動一連串動作,改變 App 的外觀並更新狀態與資料;動作完成後控制權回到應用程式,取出下一個事件。
以上是本篇全部內容。理解「事件佇列 → 視窗 → view/first responder → responder chain」這條路徑,之後看觸摸事件與 responder 的相關文件都會順暢很多。希望對大家有幫助。