我有几天这个问题了,我没有做错什么。
我的应用程序基本上只是创建一些计时器。我需要阻止它们并创建新的。但是目前停止它们是行不通的。
self.timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target:self, selector: "timerDidEnd:", userInfo: "Notification fired", repeats: false)
那是我的计时器
func timerDidEnd(timer:NSTimer){ createUnrepeatedAlarmWithUpdateInterval() }
因为我的计时器不想停止,所以我目前正在使用未重复的计时器,并在计时器停止后自行启动。
func stopAlarm() { if self.timer != nil { self.timer!.invalidate() } self.timer = nil self.timer = NSTimer() }
这就是我停止计时器的方式。
alarmManager.stopAlarm() alarmManager.createUnrepeatedAlarmWithUpdateInterval()
我stopAlarm()在创建新计时器之前先调用该函数。
stopAlarm()
我真的不知道我在做什么错,所以我很感谢每个答案:)
class AlarmManager: ViewController{ private var timer : NSTimer? private var unrepeatedTimer : NSTimer? private let notificationManager = NotificationManager() private var current = NSThread() private let settingsViewController = SettingsViewController() func createRepeatedAlarmWithUpdateInterval(){ var timeInterval:NSTimeInterval = settingsViewController.getUpdateIntervalSettings() if timer == nil{ timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: "repeatedTimerDidEnd:", userInfo: "Notification fired", repeats: true) } } func repeatedTimerDidEnd(repeatedTimer:NSTimer){ ConnectionManager.sharedInstance.loadTrainings(settingsViewController.getServerSettings()) createUnrepeatedAlarm(10) } func createUnrepeatedAlarm(timeInterval:Double){ unrepeatedTimer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: "unrepeatedTimerDidEnd:", userInfo: "Notification fired", repeats: false) } func unrepeatedTimerDidEnd(unrepeatedTimer:NSTimer){ notificationManager.createNotification(self, reminderType: NotificationManager.ITEMRATINGREMINDER) notificationManager.createNotification(self, reminderType: NotificationManager.ITEMREMINDER) print("UnrepeatedAlarm ended") } func stopAlarm(){ print("StopAlarm triggered") if (timer != nil) { print("stoptimer executed") timer!.invalidate() timer = nil } if (unrepeatedTimer != nil) { unrepeatedTimer!.invalidate() unrepeatedTimer = nil } } }
多数民众赞成在整个类的代码。也许有帮助:D
安全启动和停止计时器的常用方法是
var timer : NSTimer? func startTimer() { if timer == nil { timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: "timerFired", userInfo: nil, repeats: true) } } func stopTimer() { if timer != nil { timer!.invalidate() timer = nil } }
startTimer()开始只有当它的定时器nil和stopTimer()停止它,只有当它不是nil。
startTimer()
nil
stopTimer()
您只需要在创建/启动新计时器之前停止计时器。
在 Swift 3中 替换
NSTimer
Timer
NSTimer.scheduledTimerWithTimeInterval(
Timer.scheduledTimer(timeInterval:
selector: "timerFired"
selector: #selector(timerFired)