声明为类变量的swift定时器不会调用选择器

时间:2017-04-02 15:01:58

标签: ios swift timer

我需要能够从几个不同的函数中使一个计时器失效并重启。

为了做到这一点,我想我需要将我的计时器创建为类变量。

当我在函数的本地范围内创建计时器时,它工作正常,但我无法将其与其他函数无效。

但是,当我将它移动到类级别定义的变量时,类型为:Timer,它无法调用选择器函数。我没有任何错误。

我在viewDidAppear:

中有这个
self.timer? = Timer.scheduledTimer(timeInterval: 0.25, target: self, selector: #selector(UploadViewController.readFromBean), userInfo: nil, repeats: true)

以下是我的选择器设置方式:

func readFromBean(){
    print("reading from bean")
    if myBean != nil{
        myBean?.readAccelerationAxes()
        myBean?.readTemperature()
        myBean?.readScratchBank(1)
        myBean?.readScratchBank(2)
        myBean?.readScratchBank(3)
        myBean?.readScratchBank(4)
        myBean?.readScratchBank(5)

    }
}

1 个答案:

答案 0 :(得分:0)

我看到您喜欢其中一条评论,但认为我会分享成功使用的策略。在这种情况下,TimerAppDelegate中。

该类如下:

class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
    // lots of stuff removed 
    var loadOrdersTimer: Timer?

    // ... blah blah ... application specific methods

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        if let loadOrdersTimer = self.loadOrdersTimer? {
            loadOrdersTimer.invalidate()
            self.loadOrdersTimer = nil
        }
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        setOrderLoadingTimer()
    }

    func setOrderLoadingTimer() {
        self.loadOrdersTimer = Timer.scheduledTimer(timeInterval: intervalSeconds, target: self, selector: #selector(self.loadOrders), userInfo: nil, repeats: true)
    }

    @objc func loadOrders() {
        // do the work for which the Timer was scheduled
    }

}