【问题标题】:App stays in Activity Monitor after it has been quit应用退出后仍保留在活动监视器中
【发布时间】: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 试图在退出前保存数据。全部删除。

标签: swift macos


【解决方案1】:

这修复了它:

    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        return true
    }

还要确保 Core Date 被禁用,或者 Core Data 正确保存内容(如果没有,它不会“实际上”退出应用程序)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 2015-05-25
    • 2013-07-20
    相关资源
    最近更新 更多