sword in the stone   Hayne of Tintagel
Mac OS X  /  Programming  /  Event Handling

Event Handling

I wrote the following two programs while investigating how to port a cross-platform toolkit that does its own event handling.

TestCFRunLoop

The TestCFRunLoop program is intended as an illustration of how to integrate socket-activity in a program based on the Foundation framework and using CFRunLoop. This program has no graphical user-interface. It sets up a server socket using the BSD-level APIs and adds this socket as an event source to CFRunLoop. The program acts as a trivial web server that responds to all requests sent to port 1234 with "Hello World!". This program is derived from a sample program posted to the "Cocoa-Dev" mailing list by Douglas Davidson.

TestEvent

The TestEvent program illustrates how to break up the opaque NSApplicationMain function into its component parts in order to gain more control over the handling of events in a Cocoa program. This program has its own explicit event loop that uses the NSApplication method 'nextEventMatchingMask' to get each event, prints out details on that event, and then dispatches the event via NSApplications's 'sendEvent' method. This program has two other sources of 'events': Note that the timer 'events' and the socket 'events' do get received even though I never call CFRunLoopRun() or -[NSRunLoop run].

Note added Sept 10, 2003:
At the time I wrote this code I didn't fully understand the purpose of the NSAutoreleasePool. I now realize that the pool should get released each time through the loop - but I haven't yet taken the time to revise the code.

These projects illustrate a few aspects of programming for Mac OS X:

download the TestCFRunLoop project files

download the TestEvent project files
(Note that these projects require the Apple Developer Tools - I used the August 2002 release)

Another program of interest is Bill Bumgarner's "NoisyApp", available from his web site. It uses a subclass of NSApplication that poses as the NSApplication class to print out details on each event.