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
Submitted by Jonathan Mitchell on Thu, 01/07/2010 - 16:32

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
Let us know you are human.
12 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.