gpt4 book ai didi

swift - 定时器在停用后继续触发

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

我的应用程序中有一个“AFK”检测器。然而它的行为非常奇怪,我真的不知道为什么。请注意,我在应用程序中还有其他计时器,但它们有自己的变量名称,并且我任何时候都不会交叉它们。我认为它们都是独立的,除非它们都在同一个线程上运行或者发生了一些“幕后”恶作剧。这是管理它的代码:

func resetRoundtimer() {
roundTime = 75
}

@objc func updateRoundTimer() {
if roundTime < 0.5 {
print ("Round time is up!")
timeRemaining.invalidate()
skipTurnDueToInactivity()
timerActivity.stopAnimating()
skipTurn = true
} else {
roundTime -= 0.5
}
timerLabel.text = String(format: "%.01f", roundTime)
}

func startRoundTimer() {
timeRemaining = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.updateRoundTimer), userInfo: nil, repeats: true)
timerActivity.startAnimating()
}

这会触发“由于不活动而跳过”,这是另一个功能,它还会计算您 AFK 的次数,如果有 3 次,您应该因 AFK 时间太长而断开连接:

func skipTurnDueToInactivity() {
timeRemaining.invalidate()
print ("YOU HAVE BEEN AFK LONG ENOUGH! SKIPPING TURN! \(afkSkips)")
if afkSkips == 3 {
print ("YOU HAVE BEEN AFK 3 TIMES, DISCONNECTING YOU FROM MATCH DUE TO INACTIVITY")
print("You ded son!")
sendData(key: DID_ELIMINATE, stage: currentStage, int: nil, double: nil, player: nil, notes: nil)
didEliminatePlayer(playerDed: GKLocalPlayer.localPlayer())
} else {
afkSkips += 1
}
}

这是控制台输出:

Round time is up!
YOU HAVE BEEN AFK LONG ENOUGH! SKIPPING TURN! 0
AFK hostQ
Round time is up!
YOU HAVE BEEN AFK LONG ENOUGH! SKIPPING TURN! 1
AFK hostQ
Round time is up!
YOU HAVE BEEN AFK LONG ENOUGH! SKIPPING TURN! 2
AFK hostQ
Round time is up!
YOU HAVE BEEN AFK LONG ENOUGH! SKIPPING TURN! 3
YOU HAVE BEEN AFK 3 TIMES, DISCONNECTING YOU FROM MATCH DUE TO INACTIVITY
You ded son!

如果我明确地使计时器“无效”,为什么它会继续触发skipTurn函数?

最佳答案

根据Apple's docs :

The object to which to send the message specified by aSelector when the timer fires. The timer maintains a strong reference to target until it (the timer) is invalidated.

所以你可能遇到了一个不错的retain cycle (这意味着 Timer 持有对 self 的强引用,而 self 持有对 Timer 的强引用),具体取决于您如何声明 timeRemaining 剩余变量。

尝试将其设置为:

weak var timeRemaining: Timer?

关于swift - 定时器在停用后继续触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48523619/

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