1
votes

I am creating an macOS application with a NSTimer instance in the background using this class:

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()
    }
}

Except when I terminate my app (CMD+Q) or just regularly quit my app, there is still a process of my app in Activity Monitor, event though I terminate the NSTimer in AppDelegate:

    func applicationWillTerminate(_ aNotification: Notification) {
        MainVC.repeatingTimer?.cancel()
    }

I setup my timer in the main viewDidLoad() method of my application like this:

MainVC.repeatingTimer = RepeatingTimer(timeInterval: TimeInterval(1), eventHandler: onTimerUpdate(timer:))

I also tried to delegate my main ViewController with NSWindowDelegate, and use this to try to get rid of the process, but that did also not work:

    override func viewDidAppear() {
        self.view.window?.delegate = self
    }

    func windowWillClose(_ notification: Notification) {
        MainVC.repeatingTimer?.cancel()
    }
1
Can you attach to the process after you've quit it and see what's still running in it?user1118321
I can attach to the process after I quit it, in fact, XCode still recognizes it as "running" after I quit the application and never disconnects - but the NSTimer is not running when I quit the application.Devxln
@user1118321 XCode says AppDelegate is still running, and there seems to be an com.apple.NSEventThread running, plus another Thread with 0 0x00000000 as instruction.Devxln
That's really odd! Does your applicationWillTerminate() actually get called? If you break in there, does the debugger stop?user1118321
@user1118321 thank you for referencing to that! The issue was laying on Core Data, I don't use Core Data but somehow in my appdelegate there was a lot of junk with CoreData trying to save data before quit. Removed all of them.Devxln

1 Answers

1
votes

This fixed it:

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

Also make sure Core Date is either disabled, or Core Data is saving things correctly (if not, it will not 'actually' quit the application)