6

I tried implementing the NSWindowRestoration protocol in Swift, in a non-document-based application. However, the method restoreWindowWithIdentifier is never called at application launch. Can anyone point out my mistake?

Here is a subset of the code (which compiles and runs fine):

class AppDelegate: NSObject, NSApplicationDelegate, NSWindowRestoration {

  var windowController : MyWindowController?

  func applicationDidFinishLaunching(aNotification: NSNotification?) {
    windowController = MyWindowController(windowNibName:"ImageSequenceView")
  }

  class func restoreWindowWithIdentifier(identifier: String!, state: NSCoder!, completionHandler: ((NSWindow!,NSError!) -> Void)!) {
    NSLog("restoreWindowWithIdentifier: \(identifier), state: \(state)")
  }

 }

class MyWindowController: NSWindowController {

  override func windowDidLoad() {
    super.windowDidLoad();
    window.restorationClass = AppDelegate.self
  }
}

Thanks in advance!

  • Out of curiosity, what happens when you swap the order of `super.windowDidLoad()` and setting the `window.restorationClass`. – Erik Jun 10 '14 at 03:39
  • Sorry, long travel. Just tried but does not make a difference... – Frank Dellaert Jun 19 '14 at 21:40
  • When I use `self.dynamicType` and make sure my system preferences are set to restore windows `restoreWindowWithIdentifier` on my class is called. – Bjorn Jan 13 '15 at 00:34

1 Answers1

4

You need to set a restoration class and also an identifier:

class MyWindowController: NSWindowController {
    override func windowDidLoad() {
        super.windowDidLoad()

        self.window?.restorationClass = type(of: self)
        self.window?.identifier = "MyWindow"
    }
}

extension MyWindowController: NSWindowRestoration {
    static func restoreWindow(withIdentifier identifier: String, state: NSCoder, completionHandler: @escaping (NSWindow?, Error?) -> Void) {
        if identifier == "MyWindow" {
            // Restore the window here
        }
    }
}

Of course you can also let another class restore the window, like you tried. You need to assign AppDelegate.self as the restorationClass in that case.

Also, be aware that the window restoration setting now defaults to "off", for whatever stupid reason.

DarkDust
  • 90,870
  • 19
  • 190
  • 224
  • The System Preferences window restoration setting defaulting to off caught me too. It's extremely easy to get lost in the code, wondering why nothing is working the way you expect, until you realize that this checkbox controls it all. – Ryan Jan 31 '22 at 21:16