ManthanDalal
ManthanDalal

Reputation: 1073

how to find time between touchesBegan and touchend event in iphone?

I am implementing one iphone game application in which I want to find out time between touch begin and touch end event.

Is it possible?

Please give me advice

Thanks in advance

Upvotes: 1

Views: 2679

Answers (3)

Tommy
Tommy

Reputation: 100652

A slightly different answer to those above; use the timestamp property on the UITouch object rather than getting the current time from NSDate. It's an NSTimeInterval (ie, a C integral type) rather than an NSDate object. So, e.g.

// include an NSTimeInterval member variable in your class definition
@interface ...your class...
{
    NSTimeInterval timeStampAtTouchesBegan;
}

// use it to store timestamp at touches began
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *interestingTouch = [touches anyObject]; // or whatever you do
    timeStampAtTouchesBegan = interestingTouch.timestamp // assuming no getter/setter
}

// and use simple arithmetic at touches ended
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if([touches containsObject:theTouchYouAreTracking])
    {
        NSLog(@"That was a fun %0.2f seconds", theTouchYouAreTracking.timestamp - timeStampAtTouchesBegan);
    }
}

Upvotes: 3

Matthias Bauch
Matthias Bauch

Reputation: 90117

Yes this is possible. And this is very very easy.

You save the current time (i.e. [NSDate date]) when the touch starts, and get the difference between the current time when the touch ends and the saved start time.

@interface MyViewController : UIViewController {
    NSDate *startDate;
}
@property (nonatomic, copy) NSDate *startDate;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self.startDate = [NSDate date];

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSTimeInterval ti = [[NSDate date] timeIntervalSinceDate:self.startDate];
    NSLog(@"Time: %f", ti);
}

Upvotes: 3

Aurum Aquila
Aurum Aquila

Reputation: 9126

In your header, make an NSDate property like so:

@property(nonatomic, retain) NSDate *touchesBeganDate;

Then, in the touchesBegan method, do this:

self.touchesBeganDate = [NSDate date];

And finally, in the touchEnd method:

NSDate *touchesEndDate = [NSDate date];
NSTimeInterval touchDuration = [touchesEndDate timeIntervalSinceDate:
self.touchesBeganDate];
self.touchesBeganDate = nil;

That NSTimeInterval can be used as a normal float variable.

Happy coding :)

Oh yeah, remember to @synthesize the touchesBeganDate.

Upvotes: 1

Related Questions