macosswift2nscombobox

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


Clicking UI object NSComboBox incorrectly executes comboBoxSelectionDidChange(...) before it's .stringValue changes instead of after as it's name implies. It does same as .comboBoxSelectionIsChanging.

How can I have comboBoxSelectionDidChange(...) execute after NSComboBox.stringValue actually changes?

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
    }
}

Solution

  • Using the code below executes exactly the same as any other NSComboBoxDelegate notification function. Doesn't make sense but it works.

    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
                }
            }
        })
    }