How to properly dispose of Connected Display Window and View?

I posted this question on SO as well.

I have code that opens a window and displays a view on a connected display. My goal is to detect a connection/disconnection of a connected display and show/remove the view accordingly. I have that part working fine.

The problem I am having is closing the window upon disconnection/interruption, but then if a subsequent connection is made, and upon creating the window and view again, I get a EXC_BAD_ACCESS error.

I tried a different approach by setting the connectedDisplayWindow and connectedDisplayView to nil, after calling close() on the window when a connected display is removed. Maybe I am misunderstanding the close() method?

Apple Documentation

If the window is set to be released when closed, a release message is sent to the object after the current event is completed. For an NSWindow object, the default is to be released on closing, while for an NSPanel object, the default is not to be released. You can use the isReleasedWhenClosed property to change the default behavior...

Just to make sure, I tried setting the isReleasedWhenClosed to true, but it did not change the problem.

The other thing I see in the console is about seven repeated error strings immediately upon disconnection of the connected display: 2022-04-10 10:28:11.044155-0500 External Display[95744:4934855] [default] invalid display identifier 67EE0C44-4E3D-3AF2-3447-A867F9FC477D before the notification is fired, and one more after the notification occurs: 2022-04-10 10:28:11.067555-0500 External Display[95744:4934855] [default] Invalid display 0x4e801884. Could these be related to the issues I am having?

See example code in attachments.

I commented out the nil settings for the connectedDisplayWindow and connectedDisplayView objects and the error at @main in AppDelegate went away, but then I get an error when trying to reinitialize the connectedDisplayWindow if the connected display is removed or the connection is momentarily interrupted.

Answered by southernyankee in 711302022

I got an answer on SO. As it turns out I did not understand the use of isReleasedWhenClosed setting. By changing it from true to false, I no longer have crashes when I close the window and make it nil.

Accepted Answer

I got an answer on SO. As it turns out I did not understand the use of isReleasedWhenClosed setting. By changing it from true to false, I no longer have crashes when I close the window and make it nil.

How to properly dispose of Connected Display Window and View?
 
 
Q