Swift - 计时器不会停止

Yos*_*ssi 2 timer ios swift

我有以下代码:

class firstVC: UIViewController {
    var timer : Timer?

    func scheduledTimerWithTimeInterval(){
        timer = Timer.scheduledTimer(timeInterval: 60, target: self, 
        selector: #selector(self.anotherFunc), userInfo: nil, repeats: 
        true)
    }

    override func viewDidAppear(_ animated: Bool) {
        scheduledTimerWithTimeInterval()
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图阻止计时器但没有成功:

func stopTimer() {
    if timer != nil {
        timer?.invalidate()
        timer = nil
    }
}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    stopTimer()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    stopTimer()
}
Run Code Online (Sandbox Code Playgroud)

我甚至试图把停止功能放在applicationWillResignActive And中,applicationDidEnterBackground但它没有停止:

firstVC().stopTimer()
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助,谢谢.

Dun*_*n C 9

正如其他人所说的那样,在开始新的计时器之前,你创建了多个计时器而没有杀死旧计时器.您需要确保在开始新计时器之前停止任何当前计时器.

我所做的是让我的计时器变弱.然后在尝试创建新计时器之前使用代码`myTimer?.invalidate():

class firstVC: UIViewController {
    weak var timer : Timer?

    func scheduledTimerWithTimeInterval(){
        timer?.invalidate()
        timer = Timer.scheduledTimer(timeInterval: 60, target: self, 
        selector: #selector(self.anotherFunc), userInfo: nil, repeats: 
        true)
    }
}
Run Code Online (Sandbox Code Playgroud)

通过使你的计时器变弱,唯一保持对计时器的强引用的是运行循环.然后,当它使它失效时,它会立即释放并设置为nil.通过使用可选的链接调用无效的方法,如果它已经为零,并停止它,它不会做任何会导致它,如果它正在运行去为零.

请注意,只有使用其中一种scheduledTimer()工厂方法一次性创建计时器时,此方法才有效.如果您首先尝试创建计时器然后将其添加到运行循环中,则必须使用强大的局部变量来创建它,或者在创建它时立即释放它.


Yos*_*ssi 2

经过研究,我找到了一个解决方案,
唯一对我有用的是在 AppDelegate 文件中创建函数并在需要时调用它们,
这是代码,timerSwitch 函数:

    func timerSwitch()
    {
        if (timerStatus) {
            checkStateTimer = Timer.scheduledTimer(
                timeInterval: 60, 
                target:self, 
                selector: #selector(self.yourFunction), 
                userInfo: nil, repeats: true)
        } else {
            checkStateTimer?.invalidate()
        }
    }

    func stopTimer()
    {
        timerStatus = false
        timerSwitch()

    }

    func startTimer()
    {
        timerStatus = true
        timerSwitch()

    }
Run Code Online (Sandbox Code Playgroud)

虽然“yourFunction”是计时器启动时您想要执行的操作,但
在我的例子中是发送心跳。
然后我在AppDelegate中调用timerSwitch的是以下函数:

    func applicationWillResignActive(_ application: UIApplication) {
        stopTimer()
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        stopTimer() 
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        startTimer()
    }
Run Code Online (Sandbox Code Playgroud)