类中的Swift 3计时器未触发

Pru*_*goe 2 timer swift

我有一堂课:

class GameManager {...
Run Code Online (Sandbox Code Playgroud)

在其中,我有这个功能:

func startGame() {

        msgTimer = Timer(timeInterval: 0.5, target: self, selector: #selector(typeMessage(_:)), userInfo: nil, repeats: true)

}
Run Code Online (Sandbox Code Playgroud)

和它调用的选择器:

@objc func typeMessage(_ sender:Timer) {

        if textCount > strInitText.characters.count {
            let strThisChar = strInitText[strInitText.index(strInitText.startIndex, offsetBy: textCount)]
            strDisplayText = strDisplayText + String(strThisChar)
            print(strDisplayText)
        }

    }
Run Code Online (Sandbox Code Playgroud)

但是选择器永远不会被调用。

在此处输入图片说明

Pra*_*tti 9

此计时器需要在运行循环(通过-[NSRunLoop addTimer:])上进行调度,然后才能触发。

并从主线程调用它,如下所示:

DispatchQueue.main.async { [weak self] in
        self?.msgTimer = Timer(timeInterval: 0.5, target: self, selector: #selector(self.typeMessage(_:)), userInfo: nil, repeats: true)
        RunLoop.current.add(self.msgTimer, forMode: RunLoopMode.commonModes)
}
Run Code Online (Sandbox Code Playgroud)

但是,我建议您在这种情况下使用scheduleTimer来删除这一步:

创建一个计时器并在默认模式下将其安排在当前运行循环上。

完成后一定要使计时器无效,如下所示:

self.msgTimer.invalidate()
Run Code Online (Sandbox Code Playgroud)


Cod*_*nja 6

更改

msgTimer = Timer(timeInterval: 0.5, target: self, selector: #selector(typeMessage(_:)), userInfo: nil, repeats: true)
Run Code Online (Sandbox Code Playgroud)

msgTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(typeMessage(_:)), userInfo: nil, repeats: true)
Run Code Online (Sandbox Code Playgroud)

  • 如果你的答案能解释_为什么_这是必要的,那就更好了。 (2认同)