I have a storyboard-based AppKit app written in Swift. The issue is that two of my storyboard-based NSWindowController which are trigged by segue from the main NSWindowController, the windowDidLoad() method is called twice. I can't work out why and how.
class AnotherWindowController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
// ...
print("Is this called once?")
}
}
// Prints:
// Is this called once?
// Is this called once?
Whereas the main NSWindowController, the windowDidLoad() method is called only once. I also tried opening another main NSWindowController and the result is the same as launching the app the first time.
Why is this a problem for me? I want to do some view setup in windowDidLoad() method in AnotherWindowController. Its contentViewController is a NSSplitViewController subclass. I basically want to add an NSSplitViewItem programmatically and what happens is that it is added twice because windowDidLoad() is called twice.
In order for me to mitigate this, I would have to write code to check that the NSSplitViewItem I want to add, does not exist in the view hierarchy.
I tried cleaning the build folder, deleting the segue connection and rebuilding it. I am not sure what else to do. I believe windowDidLoad() method should only be called once.
Steps to Reproduce
- Create a brand new Xcode project, choose
macOStemplate, storyboard interface andSwiftlanguage. - Create a new storyboard file and add a Window Controller from the library and make sure it is the initial controller.
- Create a new Cocoa class and make sure it is a subclass of
NSWindowController. Give it a class name. - Assign it to the new Window Controller you made for that new storyboard file.
- Edit the new
NSWindowControllerclass file by addingprint("Is this called once?")statement at the end ofwindowDidLoad()method override. - In
Main.storyboardfile, on the Main Menu, File menu, add a new menu item on top of File menu item and make a segue connection to the new storyboard file you created. - Run the app and click on that new menu item that is supposed to open the new window controller. Look at the console log and you should see the print statement is called twice.