macosnswindow

Setting a custom Id to a NSWindow


I am creating a multi-window application on macOS. Each window created by me is a NSWindow. I would like to assign a custom Id as per my need, to the created NSWindow so that I can later find the window using the Id. Is there a way to do it ?

I understand there is a property called windowNumber. However, one cannot set this to a value as they desire.

var windowNumber: Int { get }

Thanks in Advance.


Solution

  • You can use the identifier property of a NSWindow object to assign a custom id string to a window, like this:

    let myWindowIdentifier = NSUserInterfaceItemIdentifier("My window identifier")
    
    window.identifier = myWindowIdentifier
    

    To find a window using this identifier, you use code like this:

    for window in NSApp.windows {
        if window.identifier == myWindowIdentifier {
            // Do something
            break
        }
    }