gpt4 book ai didi

ios - 声明为类变量的 Swift 计时器不会调用选择器

转载 作者:行者123 更新时间:2023-11-30 12:33:21 24 4
gpt4 key购买 nike

我需要能够通过几个不同的函数使计时器失效并重新启动。

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

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

但是,当我将其移动到类级别定义的类型为 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)
}
}

最佳答案

我看到您喜欢其中一条评论,但我想我应该分享一下我成功使用的策略。在本例中,Timer 位于 AppDelegate 中。

该类如下所示:

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
}

}

关于ios - 声明为类变量的 Swift 计时器不会调用选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43169847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com