swift 2 OSX 如何在 NSComboBox.stringValue 更改后执行 comboboxSelectionDidChange?

swift 2 OSX How can I have comboboxSelectionDidChange execute after NSComboBox.stringValue changes?

单击 UI 对象 NSComboBox 会在 .stringValue 更改之前错误地执行 comboBoxSelectionDidChange(...),而不是在其名称暗示的之后执行。它与 .comboBoxSelectionIsChanging.

相同

如何让 comboBoxSelectionDidChange(...)NSComboBox.stringValue 实际更改后执行?

class ViewController: NSViewController, NSComboBoxDelegate {
    @IBOutlet weak var comboBox: NSComboBox!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.usernameComboBox.delegate = self
    }

    func comboBoxSelectionDidChange(notification: NSNotification) {
        print(usernameComboBox.stringValue)
        // PRE-selected .stringValue = "ITEM 1"
        // POST-selected .stringValue = "ITEM 2"
        // selecting either item prints PRE-selected
    }
}

使用下面的代码执行与任何其他 NSComboBoxDelegate 通知函数完全相同。没有意义,但它有效。

func comboBoxSelectionDidChange(notification: NSNotification) {
    let currentSlection = usernameComboBox.stringValue      
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        while true {
            if self.usernameComboBox.stringValue != currentSlection {
                print(self.usernameComboBox.stringValue)
                break
            }
        }
    })
}

这是一个更短的方法:

     func comboBoxSelectionDidChange(notification: NSNotification) {

    guard let stringValue = usernameComboBox.objectValueOfSelectedItem as? String else { return }
    print(stringValue)
}