基本iphone计时器示例

sta*_*rob 24 iphone objective-c

好的,我已经在线搜索,甚至在几本书中找到答案,因为我无法理解NSTimer的苹果文档.我试图在同一视图上实现2个定时器,每个定时器有3个按钮(START - STOP - RESET).

第一个计时器从2分钟开始倒计时,然后发出蜂鸣声.

第二个计时器从00:00开始无限期计时.

我假设所有代码都将写在3个不同按钮后面的方法中,但我完全迷失了尝试阅读苹果文档.任何帮助将不胜感激.

Jon*_*ugh 35

基本上你想要的是一个每1秒触发一次的事件,或者可能以1/10秒的间隔触发,你会在计时器滴答时更新你的UI.

以下将创建一个计时器,并将其添加到您的运行循环中.将计时器保存在某处,以便在需要时将其杀死.


- (NSTimer*)createTimer {

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

现在为计时器滴答写一个处理程序:

- (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
    …
}

如果用户点击按钮,您可以重置计数,或者开始或停止计时.要结束计时器,请发送无效消息:


- (void)actionStop:(id)sender {

    // stop the timer
    [myTimer invalidate];
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助你.


rob*_*che 11

我会遵循Jonathan的方法,除非你应该使用NSDate作为更新UI的参考.这意味着不是基于NSTimer更新滴答,当NSTimer触发时,您将获取NSDate与您的参考日期之间的差异.

这样做的原因是NSTimer的分辨率为50-100毫秒,这意味着如果有很多事情要使设备变慢,那么几分钟后计时器会变得非常不准确.使用NSDate作为参考点将确保实际时间和显示时间之间的唯一滞后是计算该差异和显示的渲染.