【发布时间】:2019-09-25 22:50:53
【问题描述】:
我正在使用这个类在后台创建一个带有 NSTimer 实例的 macOS 应用程序:
class RepeatingTimer {
private var timer: Timer?
init(timeInterval: TimeInterval, eventHandler: @escaping ((Timer) -> Void)) {
timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: true, block: eventHandler)
}
deinit {
cancel()
}
func cancel() {
timer?.invalidate()
}
}
除了当我终止我的应用程序 (CMD+Q) 或只是定期退出我的应用程序时,我的应用程序在 Activity Monitor 中仍有一个进程,尽管我在 AppDelegate 中终止了 NSTimer:
func applicationWillTerminate(_ aNotification: Notification) {
MainVC.repeatingTimer?.cancel()
}
我在我的应用程序的主要 viewDidLoad() 方法中设置了我的计时器,如下所示:
MainVC.repeatingTimer = RepeatingTimer(timeInterval: TimeInterval(1), eventHandler: onTimerUpdate(timer:))
我还尝试使用 NSWindowDelegate 委托我的主 ViewController,并使用它来尝试摆脱该进程,但这也不起作用:
override func viewDidAppear() {
self.view.window?.delegate = self
}
func windowWillClose(_ notification: Notification) {
MainVC.repeatingTimer?.cancel()
}
【问题讨论】:
-
您可以在退出后附加到该进程并查看其中仍在运行的内容吗?
-
我可以在退出后附加到进程,事实上,XCode在我退出应用程序后仍然将它识别为“正在运行”并且永远不会断开连接 - 但是当我退出应用程序时 NSTimer 没有运行.
-
@user1118321 XCode 说 AppDelegate 仍在运行,似乎有一个
com.apple.NSEventThread正在运行,另外还有一个以0 0x00000000为指令的线程。 -
这真的很奇怪!你的
applicationWillTerminate()真的被调用了吗?如果你在那里闯入,调试器会停止吗? -
@user1118321 感谢您参考!问题在于Core Data,我不使用Core Data,但不知何故,在我的appdelegate 中有很多垃圾,CoreData 试图在退出前保存数据。全部删除。