6 March 2021

Random Thought Update: Showing New Windows

I’ve had a bit of trouble getting new windows in Random Thought to call methods on the window delegate when they were instantiated from the storyboard programatically. The particular scenario that I was having trouble with was implementing the New” menu item. Basically I wanted clicking the menu item to create a new post window. Each post window was to have a delegate that will notify the application when it’s closes, so that I can enable or disable other menu items based on whether a post window is active.

The way I was doing this was to have the New” menu item hooked up to the following method on the AppDelegate:

class AppDelegate: NSObject, NSApplicationDelegate {

    // ...

    @IBAction func newFileClicked(_ sender: Any) {
        let storyboard = NSStoryboard(name:"Main", bundle: nil)
        let mainWindow = storyboard
                .instantiateController(withIdentifier:"mainWindowController") as! PostWindowController
        NSApplication.shared.activate(ignoringOtherApps: true)

The PostWindowController was the following:

class PostWindowController: NSWindowController, NSWindowDelegate {
    override func windowDidLoad() {
        self.window?.delegate = self
        self.shouldCascadeWindows = true
    func windowWillClose(_ notification: Notification) {
        (NSApplication.shared.delegate as! AppDelegate).notifyOfClosedPostWindow()

The windowWillClose delegate method was being properly called for the post window first shown on launch, but not for posts window instantiated within the newFileClicked action. I have no idea why this is the case. The windowDidLoad method was being called, and as far as I could see, the delegate was being set properly, but it just will not call the delegate methods.

I’ve fixed” the problem by moving away from instantiating the main window from code, and replacing it with segues between the New” menu item and post window. This seemed to have fixed the problem: the delegate methods are being called properly now. I’m guessing that something in how segues work must be involved. Obviously there’s some gap here, either in how showing windows work, or in my knowledge of how it should work. Being relatively new to this, I’m happy to assume the latter.


Previous post
On the Scriptability of Apps I like, and fully endorse, the idea from Dave Winer about all apps, both desktop and web, being fully scriptable. I know that it’s something that I
Next post
Google, Stadia and the Petro State Curse Google announced changes to Google Pay a few days ago. This is yet another service that Google is pivoting, with seemingly no awareness or care of