gpt4 book ai didi

timer - SWIFT - 多个 NSTimer

转载 作者:搜寻专家 更新时间:2023-11-01 06:24:24 24 4
gpt4 key购买 nike

尝试在 SWIFT 中管理多个 NSTimer 时,我遇到了一个小问题。无论我尝试什么,它只会使我创建的最后一个计时器无效。但我需要能够通过选择使任何计时器失效。

有没有什么方法可以创建一个引用 ID,然后我可以用它来选择我想要使之无效的特定 NSTimer?任何帮助都会很棒。

这是我的代码片段。

import UIKit

var myTimer:NSTimer!

class TimerManager: NSObject {

}

public class Timer {
// each instance has it's own handler
private var handler: (timer: NSTimer) -> () = { (timer: NSTimer) in }

public class func start(duration: NSTimeInterval, repeats: Bool, handler:(timer: NSTimer)->()) {
var t = Timer()
t.handler = handler
myTimer = NSTimer.scheduledTimerWithTimeInterval(duration, target: t, selector: "processHandler:", userInfo: nil, repeats: repeats)
}

@objc private func processHandler(timer: NSTimer) {
self.handler(timer: timer)
}
}

class countdown{
//handles the countdown for the timer and invalidates when it reaches 0
var y = 0

func begin(length:Int) {

y = length

let delta = 1
let delay = 1.0
Timer.start(delay, repeats: true) {
(t: NSTimer) in

self.y -= delta
println(self.y)

if (self.y <= 0) {
t.invalidate()
}
}
}

func end () {
println("timer stopped")
myTimer.invalidate()
}
}

然后我像这样创建计时器:

 countdownTimer.begin(120) //time length in seconds ... 120 = 2 mins

停止计时器:

 countdownTimer.end() 

最佳答案

您可以创建一个保留 NSTimer 对象的字典。请注意,timerManager 需要在全局范围内定义。希望它有所启发。

class TimerManager {

var _timerTable = [Int: NSTimer]()
var _id: Int = 0

/*! Schedule a timer and return an integer that represents id of the timer
*/
func startTimer(target: AnyObject, selector: Selector, interval: NSTimeInterval) -> Int {
var timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: target, selector: selector, userInfo: nil, repeats: true)
_id += 1
_timerTable[_id] = timer
return _id
}

/*! Stop a timer of an id
*/
func stopTimer(id: Int) {
if let timer = _timerTable[id] {
if timer.valid {
timer.invalidate()
}
}
}

/*! Returns timer instance of an id
*/
func getTimer(id: Int) -> NSTimer? {
return _timerTable[id]
}

}

// This needs to be delcared at global scope, serving as "singleton" instance of TimerManager
let timerManager = TimerManager()

以下代码创建一个新的计时器。

var aTimer = timerManager.startTimer(self, selector: Selector("timerFunction"), interval: 1)

要停止计时器,只需将 id 传递给 stopTimer(id: Int)

/* Code ... */
timerManager.stopTimer(aTimer)

另请注意 getTimer 方法返回具有 id 的实际实例。

问候

关于timer - SWIFT - 多个 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25973137/

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