理解Mac和iOS中的 Event 处理

时间:2021-10-08 23:01:38

根据现在的理解,我把event处理分为5部分,第一是,Event处理的Architecture;第二是,Event的Dispatch到first responder之前; 第三是,Event从first responder出来后;第四是,Action与Event的关系;第五是,Apple Event的处理。

1. Event Handling Architecture

下面这张图解释了在MacOSX上event处理的过程。

理解Mac和iOS中的 Event 处理

Before it dispatches an event to an application, the window server processes it in various ways; it time-stamps it, annotates it with the associated window and process port, and possibly performs other tasks as well. As an example, consider what happens when a user presses a key. The device driver translates the raw scan code into a virtual key code which it then passes off (along with other information about the key-press) to the window server in an event record. The window server has a translation facility that converts the virtual key code into a Unicode character.

In OS X, events are delivered as an asynchronous stream. This event stream proceeds “upward” (in an architectural sense) through the various levels of the system—the hardware to the window server to the Event Manager—until each event reaches its final destination: an application. As it passes through each subsystem, an event may change structure but it still identifies a specific user action.

在event到达Window Server之后,就等着发给各个Application去处理了,如果一个App是基于Cocoa的,它会使用Run Loop从Window Server中获取应该由本App处理的event。

理解Mac和iOS中的 Event 处理

从这个图可以看出,每个应用有一个Event Source与之对应。Event Source中有个Mach port用于从Window Server接收Event,然后存放在一个队列中。每个应用的Main run Loop是一个只负责从event source中取 event,如果没有event,Run Loop就会Block住,一直等到有event为止。之所以这里有个Main run loop是因为,在Cocoa应用中,每个线程都有一个run loop,主线程的run loop叫main run loop。Run loop就是一个NSRunLoop对象。Apple event一会通过Run Loop进入一个App,详细可以见Apple Event部分的描述。

2. Event Dispatch : Arriving at First Responder;

3. Event Dispatch: After First Responder;

4. Action

参考文档

1. Cocoa Event Handling Guide: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/EventArchitecture/EventArchitecture.html#//apple_ref/doc/uid/10000060i-CH3-SW2

2. Event Handling Guide for iOS:https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/event_delivery_responder_chain/event_delivery_responder_chain.html#//apple_ref/doc/uid/TP40009541-CH4-SW2

3. Mac vs. iOS event 比较:https://developer.apple.com/library/ios/documentation/general/conceptual/Devpedia-CocoaApp/Responder.html