当空格键被击中时记录时间

0 cocoa objective-c

我想在空格键被击中时记录HH:MM:SS的时间.我在研究中发现它更容易使用cocoa然后基础,因为cocoa有一个可以感知击键的NSEvent类.有一个类似的问题询问如何感知双重空格键击中但它不满足如何将其与我的程序相关联.

代码如下:

NSDate *startTime = [NSDate date ];
NSTimeInterval elaspedTime = [startTime timeIntervalSinceNow];

-(void)sendEvent:(NSEvent *) theEvent{
    NSString* spaceBarPressed = [ theEvent characters ];
    if( [spaceBarPressed isEqualToString:@"" ] ){
        if(theEvent.type == NSKeyDown )
            NSLog(@"Space bar hit" );
    }
}
Run Code Online (Sandbox Code Playgroud)

Jus*_*Boo 7

它可以这样做:

- (void)keyDown:(NSEvent *)theEvent { 

    if ([theEvent keyCode] == 49) { //Spacebar keyCode is 49
        NSLog(@"Time is: %@", [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterMediumStyle]);
    }
}
Run Code Online (Sandbox Code Playgroud)