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

标签 swift xcode timer

我的应用程序中有一个“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/

相关文章:

javascript - 如何用Javascript制作一个非常简单的倒计时器?

Java LocalDateTime/OffsetDateTime 到 Swift 4

ios - swift 1.2 "Cannot express tuple conversion"错误

ios - 在 Google Cloud Platform 中为 iOS 启用 Places API

xcode - 该应用程序在 Payload/(App ID) : number, setNumber 中引用了非公共(public)选择器:

swift - 如何实现 SpriteKit 计时器?

ios - 如何正确删除 Timer 实例

xcode - 使用swift在tableviewcell中创建tableview

ios - 如何重新加载具有不同行数的 UITableView 部分?

ios - CocoaPods 框架 : codesign is trying to use a code signing identity I've deleted