NSEvent Timestamp

Content

NSEvent Timestamp

Posted in:

A category on NSEvent suitable for NSEvent time stamping.

NSEvent provides a number of factory methods which take a timestamp argument, but provides no method of generating a system time timestamp. This may indicate why some of the AppKit generated events in fact have a zero timestamp.

Some reading seemed to suggest that NSEvent -timestamp value was derived from a mach clock. This does seem to be born out in practice.
Presumably interrupt driven keyboard and mouse events are timestamped with the time the interrupt handler processes the event.

I found NSEvent +timestamp useful in a situation where I wanted to filter events by timestamp but didn't want to necessarily remove them from the event queue.


@interface NSEvent(Timestamp)
+ (NSTimeInterval)timestamp;
@end

#import "NSEvent+Timestamp.h"
#import <mach/mach.h>
#import <mach/clock.h>

@implementation NSEvent(Timestamp)

/*
 
 timestamp
 
 */
+ (NSTimeInterval)timestamp
{	
	// get clock right
	clock_serv_t host_clock;
	kern_return_t status = host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &host_clock);
	if (!status) {
		return 0.f;
	}
	
	// get time
	mach_timespec_t now;
	clock_get_time(host_clock, &now);
	
	return (NSTimeInterval)now.tv_sec + ((NSTimeInterval)now.tv_nsec)/1000000000.0f;
}
@end