目标C如何制作一个从两分钟倒计时的计时器?

0 xcode timer objective-c nstimer ios

我在网上寻找答案,但没有运气.我试过了

- (void)viewDidLoad {

[super viewDidLoad];

twoMinTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timer) userInfo:nil repeats:YES]; }

- (void)timer {
for (int totalSeconds = 120; totalSeconds > 0; totalSeconds--){

timerLabel.text = [self timeFormatted:totalSeconds];

if ( totalSeconds == 0 ) {

   [twoMinTimer invalidate];

   } } }
Run Code Online (Sandbox Code Playgroud)

但它没有用,当我去那个视图时,标签从2.00变为0.01然后它就停止了.

任何建议都将不胜感激 - 菲利普

Cod*_*aFi 7

你正在使用一个for for循环而不是简单地减少总时间.试试这个:

- (void)viewDidLoad {

    [super viewDidLoad];
    totalSeconds = 120;
    twoMinTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                   target:self
                                                 selector:@selector(timer)
                                                 userInfo:nil
                                                  repeats:YES];
}

- (void)timer {
    totalSeconds--;
    timerLabel.text = [self timeFormatted:totalSeconds];
    if ( totalSeconds == 0 ) {
        [twoMinTimer invalidate];
    } 
}
Run Code Online (Sandbox Code Playgroud)

声明totalSeconds为int.

编辑:我非常感谢@JoshCaswell和@MichaelDorst分别提出建议和代码格式.NSTimer绝不是时间的准确表示,对于秒表或计数器来说绝对不够准确.相反,NSDate +dateSinceNow将是一个更准确的替代品,甚至是逐渐降低的水平CFAbsoluteTimeGetCurrent(), mach_absolute_time()并且精确到亚毫秒

  • BTW,实际上是关于主题的:对于实时"秒表",通常最好检查日期而不是仅减少计数器 - 即使"NSTimer"被延迟,显示也将始终正确. (4认同)