Tracing Events in Cocoa

Introduction

Cocoa has the ability to log each event (as described by an NSEvent object) as it is sent. This can be a very useful debugging tool when developing Cocoa applications. I have only used this with Objective C applications however the same techniques should work for Java.

From The Command Line

You can turn on event tracing from the command line using the argument -NSTraceEvents YES to your application. i.e.

/Applications/TextEdit.app/Contents/MacOS/TextEdit -NSTraceEvents YES

In this case the trace information appears on stderr.

Using the Defaults Database

You can turn on event tracing for an application on a semi-permanent basis by setting a default in the defaults database. You need to know the application's identifier (usually a string in reverse domain notation such as com.apple.TextEdit) for this. You can usually find this by looking at the CFBundleIdentifier entry in the applications Info.plist or by looking at the name of it's preferences file.

Assuming the identifier in question is com.apple.TextEdit you can switch on tracing by setting the application's NSTraceEvents default to YES.

defaults write com.apple.TextEdit NSTraceEvents YES

To switch off tracing you can set the default to NO or just delete it all together.

defaults delete com.apple.TextEdit NSTraceEvents

When enabling tracing this way the trace information is sent to the system console which you can view with Console.app.

Example Output

The output of NSTraceEvents can be quit verbose but an example of a keyDown event may look like:

 
2002-12-02 00:40:01.892 DocEdit[1123] Received event: KeyDown at: 558.0,342.0 time: 6451 flags: 0 win: 1568 ctxt: c90b data: 0,0,0,115,1,115
2002-12-02 00:40:01.893 DocEdit[1123]     In Application: NSEvent: type=KeyDown loc=(-1,573) time=27707.7 flags=0 win=0 winNum=1568 ctxt=0xc90b chars="s" unmodchars="s" repeat=0 keyCode=1
2002-12-02 00:40:01.894 DocEdit[1123]     In Window: NSEvent: type=KeyDown loc=(-1,573) time=27707.7 flags=0 win=0 winNum=1568 ctxt=0xc90b chars="s" unmodchars="s" repeat=0 keyCode=1