之前代码:
func startMarkHasRead(curMsgTVC:MessageTableViewController) {
gLog.debug("curMsgTVC=\(curMsgTVC), name=\(curMsgTVC.contactItem.name), id=\(curMsgTVC.contactItem.id)")
let startTime:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, 0)
let intervalInSec:UInt64 = MarkHasReadIntervalInSec * NSEC_PER_SEC
let leeway:UInt64 = 0 * NSEC_PER_SEC
dispatch_source_set_timer(self.markHasReadTimer, startTime, intervalInSec, leeway)
dispatch_source_set_event_handler(self.markHasReadTimer, {
self.tryMarkHasRead(curMsgTVC)
})
dispatch_resume(self.markHasReadTimer)
}
func endMarkHasRead(curMsgTVC:MessageTableViewController) {
gLog.debug("curMsgTVC=\(curMsgTVC), name=\(curMsgTVC.contactItem.name), id=\(curMsgTVC.contactItem.id)")
dispatch_source_cancel(self.markHasReadTimer)
}
发现第二次执行到:
dispatch_source_cancel(self.markHasReadTimer)
就崩溃了:
后来改为:
func startMarkHasRead(curMsgTVC:MessageTableViewController) {
dispatch_source_cancel(self.markHasReadTimer)
gLog.debug("curMsgTVC=\(curMsgTVC), name=\(curMsgTVC.contactItem.name), id=\(curMsgTVC.contactItem.id)")
let startTime:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, 0)
let intervalInSec:UInt64 = MarkHasReadIntervalInSec * NSEC_PER_SEC
let leeway:UInt64 = 0 * NSEC_PER_SEC
dispatch_source_set_timer(self.markHasReadTimer, startTime, intervalInSec, leeway)
dispatch_source_set_event_handler(self.markHasReadTimer, {
self.tryMarkHasRead(curMsgTVC)
})
dispatch_resume(self.markHasReadTimer)
}
func endMarkHasRead(curMsgTVC:MessageTableViewController) {
gLog.debug("curMsgTVC=\(curMsgTVC), name=\(curMsgTVC.contactItem.name), id=\(curMsgTVC.contactItem.id)")
dispatch_source_cancel(self.markHasReadTimer)
}
问题依旧。
后来注意到了:
ios – Swift – Do something every x minutes – Stack Overflow
中的:
dispatch_source_cancel(timer)
之后的:timer = nil
dispatch source cancel crash
iphone – dispatch_source_cancel on a suspended timer causes EXC_BAD_INSTRUCTION – Stack Overflow
iOS 中的timer — NSRunLoopCommonModes和Timer .NSThread和Timer.GCD中的Timer – Dev_APP的专栏 – 博客频道 – CSDN.NET
好像可以suspend?
去用:
func endMarkHasRead(curMsgTVC:MessageTableViewController) {
gLog.debug("curMsgTVC=\(curMsgTVC), name=\(curMsgTVC.contactItem.name), id=\(curMsgTVC.contactItem.id)")
// dispatch_source_cancel(self.markHasReadTimer)
dispatch_suspend(self.markHasReadTimer)
}
即可
-》
之后,再去重复的调用:
dispatch_resume(self.markHasReadTimer)
就不会崩溃了。