NSViewController User Interface State Restoration

To achieve aforementioned effect let’s create NSSearchField and a custom class named RestoredWindow containing just one property:

import Cocoa

class RestoredWindow: NSWindow {

    override class var restorableStateKeyPaths: [String] {
        return ["self.contentViewController.searchField.stringValue"]

Assign this custom class to Window Controller in Identity Inspector.

Next, let’s bind searchField.stringValue property to ViewController in Value section of Bindings Inspector.

import Cocoa

class ViewController: NSViewController {

    @IBOutlet weak var searchField: NSSearchField!

    override func viewDidLoad() {

After this, make sure you haven’t checked Close windows when quitting an app option in your System Preferences -> General tab.

Now, entered text in NSSearchField restored after quitting and launching the app again.


I’ve tried the same way as you but failed too. This approach doesn’t work for me:

override func encodeRestorableState(with coder: NSCoder) {
    coder.encode(searchField.stringValue, forKey: "restore")
    super.encodeRestorableState(with: coder)

override func restoreState(with coder: NSCoder) {   
    if let state = coder.decodeObject(forKey: "restore") as? NSSearchField {
        searchField.stringValue = state
    super.restoreState(with: coder)

Leave a Comment