DonnellyOverflow
DonnellyOverflow

Reputation: 4195

Time between 2 events

I haven't been programming in iOS for long but I was just wondering if anyone could help. I have a IBAction function and every time it is pressed increases a counter so I can see how many times it's been pressed. But I want to add functionality so when it's pressed I can display the time between each press. So if they press the button a one pops up. Then they press it again and 2 button presses pops up but also the amount of time since they pressed it. I'm not sure how to implement this because I'm not sure how I would find the time of the event. There is UIEvent's timestamp, but I'm not entirely sure how to use it.

Upvotes: 0

Views: 1358

Answers (2)

Casey Fleser
Casey Fleser

Reputation: 5787

Unless you need extreme accuracy it's probably enough to get the current time when your IBAction method is called in which case you could do something like this:

- (IBAction) buttonAction: (id) inButton
{
    NSDate              *now = [NSDate date];

    if (self.lastEventTime != nil) {
        NSTimeInterval      timeSinceLast = [now timeIntervalSinceDate: self.lastEventTime];

        NSLog(@"time since last press: %f seconds", timeSinceLast);
    }

    self.lastEventTime = now;
}

Here's how that might look in Swift:

class SomeController: UIViewController {
    var lastEventTime                   : NSDate?

    @IBAction func buttonAction(inButton: AnyObject) {
        let now = NSDate()

        if let lastEventTime = self.lastEventTime {
            let timeSinceLast = now.timeIntervalSinceDate(lastEventTime)

            println("time since last press: \(timeSinceLast) seconds")
        }

        self.lastEventTime = now
    }
}

Upvotes: 3

TMob
TMob

Reputation: 1278

You could have a NSDate property which you assign every time, the event is fired. You then always compare the difference between the property and the current time.

@property (nonatomic) NSDate *lastEventDate;

- (IBAction) clicked:(id)sender{
      NSDate *now = [NSDate date];
      NSTimeInterval differenceBetweenDatesInSeconds = [self.lastEventDate timeIntervalSinceDate:now];

      //Do something with the interval (show it in the UI)
      [self setLastEventDate:now];
}

Upvotes: -2

Related Questions