Basic iphone timer example

2020-06-07 04:34发布

Okay, I have searched online and even looked in a couple of books for the answer because I can't understand the apple documentation for the NSTimer. I am trying to implement 2 timers on the same view that each have 3 buttons (START - STOP - RESET).

The first timer counts down from 2 minutes and then beeps.

The second timer counts up from 00:00 indefinitely.

I am assuming that all of the code will be written in the methods behind the 3 different buttons but I am completely lost trying to read the apple documentation. Any help would be greatly appreciated.

2条回答
够拽才男人
2楼-- · 2020-06-07 04:59

Basically what you want is an event that fires every 1 second, or possibly at 1/10th second intervals, and you'll update your UI when the timer ticks.

The following will create a timer, and add it to your run loop. Save the timer somewhere so you can kill it when needed.


- (NSTimer*)createTimer {

    // create timer on run loop
    return [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTicked:) userInfo:nil repeats:YES];
}

Now write a handler for the timer tick:

- (void)timerTicked:(NSTimer*)timer {

    // decrement timer 1 … this is your UI, tick down and redraw
    [myStopwatch tickDown];
    [myStopwatch.view setNeedsDisplay]; 

    // increment timer 2 … bump time and redraw in UI
    …
}

If the user hits a button, you can reset the counts, or start or stop the ticking. To end a timer, send an invalidate message:


- (void)actionStop:(id)sender {

    // stop the timer
    [myTimer invalidate];
}

Hope this helps you out.

查看更多
成全新的幸福
3楼-- · 2020-06-07 05:02

I would follow Jonathan's approach except you should use an NSDate as your reference for updating the UI. Meaning instead of updating the tick based on the NSTimer, when the NSTimer fires, you take the difference between NSDate for now and your reference date.

The reason for this is that the NSTimer has a resolution of 50-100 ms which means your timer can become pretty inaccurate after a few minutes if there's a lot going on to slow down the device. Using NSDate as a reference point will ensure that the only lag between the actual time and the time displayed is in the calculation of that difference and the rendering of the display.

查看更多
登录 后发表回答