定时器在停用后继续点火

时间:2018-01-30 14:19:57

标签: swift xcode timer

我有一个" AFK"检测器在我的应用程序然而,它表现得非常奇怪,我真的不知道为什么。注意我在应用程序中有其他计时器,但是他们有自己的变量名称,我不会随时交叉。我认为他们都是独立的,除非他们都以某种方式运行在相同的线程或某些“引擎盖下”#34;恶作剧发生了。以下是管理它的代码:

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()
    }

由于不活动而触发&#34;跳过&#34;这是另一个功能,也计算你已经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!

如果我清楚&#34;无效&#34;计时器为什么继续触发skipTurn函数?

1 个答案:

答案 0 :(得分:0)

根据Apple's docs

  

定时器触发时,aSelector指定的消息发送到的对象。计时器保持对目标的强引用,直到它(计时器)无效。

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

尝试将其设置为:

weak var timeRemaining: Timer?