Calculating intervals between events
What is a good way to record time between user events on iPhon开发者_开发知识库e? ie. time between pressing Button_A and Button_B.
A more accurate way than using [NSDate date]
is to use the timestamp
property of the UIEvent
. To get the UIEvent
, make sure you use the two-argument form for the target-action method.
- (IBAction)buttonPressed:(UIButton *)sender event:(UIEvent *)event
{
NSTimeInterval timestamp = event.timestamp;
NSTimeInterval secondsSinceLastEvent = timestamp - lastTimestamp;
}
Well, you can adapt such code to your situation :
NSDate *start = [NSDate date];
//do some stuff
NSLog(@"%f seconds elapsed", [[NSDate date] timeIntervalSinceDate:start]);
For example, write start = [NSDate date];
in your Button_A action, and NSLog(@"%f seconds elapsed", [[NSDate date] timeIntervalSinceDate:start]);
in your Button_B action.
Create an NSDate object when the buttonA was pressed and then whenever the buttonB is pressed get the time elapsed since now by like this:
[[NSDate now] timeIntervalSince:buttonADate];
精彩评论