How to implement NSWindowRestoration in Swift?
Asked Answered
S

1

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!

Stalemate answered 10/6, 2014 at 0:50 Comment(3)
Out of curiosity, what happens when you swap the order of super.windowDidLoad() and setting the window.restorationClass.Goldi
Sorry, long travel. Just tried but does not make a difference...Stalemate
When I use self.dynamicType and make sure my system preferences are set to restore windows restoreWindowWithIdentifier on my class is called.Disappearance
A
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.

Anthraquinone answered 28/6, 2017 at 9:3 Comment(1)
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.Hurtado

© 2022 - 2024 — McMap. All rights reserved.