0

I have a document-based macOS application, which is a basic text editor. The default behavior is to create a new window for every opened document. But I want to only have one window displayed at a time and when opening a document or creating a new one, this should happen in the same window and thus replace the old document.

I've tried to do some hacking in the makeWindowControllers method from NSDocument by not instantiating a new window controller but reusing an old one. But after some problems with this approach, I figured this is not the right way to go. I was wondering if there is a common approach to this problem.

This is the code I've tried

class Document: NSDocument {
    
    static var sharedWindow: NSWindowController?
    
    override func makeWindowControllers() {
        // Instaniate window controller there is none
        if Document.sharedWindow == nil {
            // Returns the Storyboard that contains your Document window.
            let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
            Document.sharedWindow = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("Document Window Controller")) as? NSWindowController
        }

        guard let sharedWindow = Document.sharedWindow else { return }
        if let previousDocument = sharedWindow.document as? NSDocument {
            previousDocument.close()
        }

        self.addWindowController(sharedWindow)

        sharedWindow.contentViewController?.representedObject = content
        (sharedWindow.contentViewController as? ViewController)?.handleOpenDocumentOperation()
    }

    ...
}
Codey
  • 1,131
  • 2
  • 15
  • 34
  • See [Change document in open window in macOS app](https://stackoverflow.com/questions/57759693/change-document-in-open-window-in-macos-app) – Willeke Sep 30 '20 at 19:39
  • Thanks, I've tried this solution and updated my question. The problem with this is, that now when a new document (not yet saved) has changes, the alert sheet about these unsaved changes doesn't appear. Instead the new window is just presented. – Codey Oct 01 '20 at 07:29
  • Same goes with already saved files which have unsaved changes. Neither is the alert sheet displayed nor does autosaving work. When I add `previousDocument.save(self)`, then the saved files will be saved. For unsaved files, the alert sheet is displayed but immediately dismissed by the new window. – Codey Oct 01 '20 at 07:38

0 Answers0