Search code examples
macoscocoaappkit

NSSearchField occasionally causing an NSInternalInconsistencyException


The exception is "NSWindow: -_oldFirstResponderBeforeBecoming is not a valid message outside of a responder's implementation of -becomeFirstResponder." However, according to the stack trace the message is called from becomeFirstResponder, so I don't know what I am doing wrong. This is an intermittent error.

The user presses a key command sequence, which fires a menu item, which sends a message to the key window controller, which tells a search field on the window to become first responder.

Here's a summarised stack trace::

[NSException raise:format:]
[NSWindow _oldFirstResponderBeforeBecoming]
[NSSearchField becomeFirstResponder]
[MyWindowController focusSearchField]
[NSApplication sendAction:to:from:]
[NSMenu performKeyEquivalent:]

The implementation of the window controller's action is very simple:

public var searchField: NSSearchField?
@IBAction public func focusSearchField(sender: AnyObject) {
    searchField?.becomeFirstResponder()
}

Thanks for any assistance.


Solution

  • I found a solution here.

    Instead of using becomeFirstResponder, you should use NSWindow's makeFirstResponder method.

    public var searchField: NSSearchField?
    @IBAction public func focusSearchField(sender: AnyObject) {
        searchField?.window?.makeFirstResponder(searchField!)
    }