Swift:如果计时器从函数启动,如何使计时器无效? [英] Swift: How to invalidate a timer if the timer starts from a function?

查看:50
本文介绍了Swift:如果计时器从函数启动,如何使计时器无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这样的函数中有一个 timer 变量:

I have a timer variable in a function like this:

timer = NSTimer()

func whatever() {
   timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerbuiltingo", userInfo: nil, repeats: true)
}

当我尝试在生成的 timerbuiltingo 函数中停止计时器时,如下所示:

when I try to stop the timer in the resulting timerbuiltingo function like this:

func timerbuiltingo() {
   timer.invalidate()
   self.timer.invalidate()
}

它并没有阻止它.我该怎么做?

It doesn't stop it. How should I be doing this?

推荐答案

如果您需要能够在任何时间点停止计时器,请将其设为实例变量.

If you need to be able to stop the timer at any point in time, make it an instance variable.

如果您只需要在调用它的方法中停止它,您可以让该方法接受一个 NSTimer 参数.调用该方法的定时器会将自身传入.

If you will only ever need to stop it in the method it is called, you can have that method accept an NSTimer argument. The timer calling the method will pass itself in.

class ClassWithTimer {
    var timer = NSTimer()

    func startTimer() {
        self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerTick:", userInfo: nil, repeats: true)
    }

    @objc func timerTick(timer: NSTimer) {
        println("timer has ticked")
    }
}

有了这个设置,我们现在可以调用 self.timer.invalidate() 或者,在 timerTick 中,我们可以调用 timer.invalidate()(指的是调用该方法的定时器).

With this set up, we can now either call self.timer.invalidate() or, within timerTick, we can call timer.invalidate() (which refers to the timer which called the method).

这篇关于Swift:如果计时器从函数启动,如何使计时器无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆