(NSTimer)创建定时器倒计时

Mat*_*uys 6 xcode objective-c nstimer

我正在尝试创建一个简单的倒数计时器,以便当玩家进入我的游戏时,计时器从60开始下降到0.这看起来很简单,但我对如何写这个感到困惑.

到目前为止,我在GameController.m中创建了一个方法,如下所示:

-(int)countDownTimer:(NSTimer *)timer {
    [NSTimer scheduledTimerWithTimeInterval:-1
                                 invocation:NULL
                                    repeats:YES];
    reduceCountdown = -1;
    int countdown = [[timer userInfo] reduceCountdown];
    if (countdown <= 0) {
        [timer invalidate];
    }
    return time;
}
Run Code Online (Sandbox Code Playgroud)

在游戏开始时,我将整数Time初始化为60.然后在ViewController中设置标签.但是在我编译代码的那一刻,它只是将标签显示在60并且根本没有减少.

任何帮助将不胜感激 - 我是Objective-C的新手.


编辑

在一些帮助下,我现在将代码分成两个单独的方法.代码现在看起来像这样:

-(void)countDown:(NSTimer *)timer {
    if (--time == 0) {
        [timer invalidate];
        NSLog(@"It's working!!!");
    }
}

-(void)countDownTimer:(NSTimer *)timer {
    NSLog(@"Hello");
    [NSTimer scheduledTimerWithTimeInterval:1
                                      target:self
                             selector:@selector(countDown:)
                                      userInfo:nil
                                      repeats:YES];
}
Run Code Online (Sandbox Code Playgroud)

但是,代码仍然无法正常运行,当我从View Controller调用方法[game countDownTimer]时,它会断言:"无法识别的选择器发送到实例".任何人都可以解释这里有什么问题吗?

das*_*ght 11

你的代码有几个问题:

  • 您在时间间隔内传递了错误的参数 - 负数被解释为0.1 ms
  • 你正在调用错误的重载 - 你应该传递一个调用对象,但你传递了一个NULL
  • 您将要执行的代码与计时器初始化一起放在计时器上 - 需要在计时器上执行的代码应该进入单独的方法.

你应该调用带有选择器的重载,并传递1间隔,而不是-1.

声明NSTimer *timerint remainingCounts,再加入

timer = [NSTimer scheduledTimerWithTimeInterval:1
                                         target:self
                                       selector:@selector(countDown)
                                       userInfo:nil
                                        repeats:YES];
remainingCounts = 60;
Run Code Online (Sandbox Code Playgroud)

到你想要开始倒计时的地方.然后添加countDown方法本身:

-(void)countDown {
    if (--remainingCounts == 0) {
        [timer invalidate];
    }
}
Run Code Online (Sandbox Code Playgroud)