NSViewControllers and NSViews are not getting rest

2019-04-25 17:37发布

问题:

in Apple's documentation they say that in case of document-based apps you should get restoration calls (restoreStateWithCoder: and encodeRestorableStateWithCoder:) to NSApplication, NSWindow, NSWindowController and then the whole responder chain (here).

I want to implement this, but I'm getting the restoration calls only in NSWindowController/NSDocument subclass, not the NSViews or NSViewControllers.

I created a new document-based app to test this (here), but I get the restoration calls only in the NSDocument subclass but not the NSViewController or NSView.

Code from the test project:

NSDocument subclass (restoration works):

class Document: NSDocument {

  override func restoreState(with coder: NSCoder) {
    super.restoreState(with: coder)
    // Gets called after reopening the app
  }

  override func encodeRestorableState(with coder: NSCoder) {
    super.encodeRestorableState(with: coder)
    // Gets called when leaving the window for the first time
  }


}

NSViewController subclass (restoration doesn't work):

class ViewController: NSViewController {

  override func restoreState(with coder: NSCoder) {
    super.restoreState(with: coder)
    // Not called
  }

  override func encodeRestorableState(with coder: NSCoder) {
    super.encodeRestorableState(with: coder)
    // Not called
  }

}

NSView subclass (restoration doesn't work):

class MyView: NSView {

  override func restoreState(with coder: NSCoder) {
    super.restoreState(with: coder)
    // Not called
  }

  override func encodeRestorableState(with coder: NSCoder) {
    super.encodeRestorableState(with: coder)
    // Not called
  }
}

回答1:

I just ran into the same problem. It seems the state preservation system uses the identifier property to determine whether to encode/restore the state of an object.

According to the documentation, the identifier is automatically populated when an object is loaded from a NIB file. However, it needs to be set manually if an object is created programmatically.