Application terminates on sleep even if windows are not closed

I've received some reports from users of my macOS app that the application quits when putting their Mac to sleep after hiding all windows.

The NSApplicationDelegate implements applicationShouldTerminateAfterLastWindowClosed and returns true. However this method is called even though there are still windows open.

Unfortunately I'm not able to reproduce the issue, but here are the steps to reproduce according to the user:

  1. Open app (single NSWindow visible)
  2. Press Command-H to hide the single window
  3. Put Mac to sleep

The app is terminated when the Mac wakes. These steps have been confirmed by a user in Safe Mode, so I expect no interference of other applications (macOS 15.1.1).

When this happens the application logs show that applicationShouldTerminateAfterLastWindowClosed is called when the Mac goes to sleep. But the main NSWindow is still open (yet hidden). The close() method on NSWindow is not called before applicationShouldTerminateAfterLastWindowClosed.

Order of events:

NSApplicationDelegate.applicationWillHide
NSApplicationDelegate.applicationWillResignActive
[...]
NSApplicationDelegate.applicationShouldTerminateAfterLastWindowClosed
NSApplicationDelegate.applicationShouldTerminate
NSApplicationDelegate.applicationWillTerminate
NSWindow.close

I assumed that applicationShouldTerminateAfterLastWindowClosed is only called after all windows are closed. Is that assumption incorrect?

Does a user-hidden NSWindow count as a closed window?

For me (and other users) the API works as expected and the app stays running when the app is hidden as the Mac sleeps. applicationShouldTerminateAfterLastWindowClosed is not called until all windows are actually closed.

I'm having a similar situation on my Macs. Whenever they sleep and then wake, Xcode wants to have quit out (my app is running in Xcode - so it is prompting me to stop the app first). If I stop my app Xcode quits as if it had been command-q'd during sleep.... I can repro on multiple Macs here.

Application terminates on sleep even if windows are not closed
 
 
Q