Detecting a change in NSTextField in ToDo challenge

I want to make it so that the Add button is only enabled if the input text field has a non-empty stringValue

Looking around I found the way to do this is to set the window controller to be the delegate of the text field and then implement the following method

    override func controlTextDidChange(obj: NSNotification) {
        addButton.enabled = !textField.stringValue.isEmpty

A couple of questions arise from this:
I would have thought this type of thing would be handled by the NSTextFieldDelegate but this does not seem to be the case.
Why does the window controller not need to be marked as a delegate for this to work? Is it because NSWindowController implements this method already hence the override?
Is this the right way to handle this?

Thanks in advance,


This is a pretty reasonable way of accomplishing this, yes. Hard to say why it is not done using a notification and not NSTextFieldDelegate. Design decisions of long ago.

The reason for the “override” keyword is also due to historical reasons. controlTextDidChange(:slight_smile: is defined as a category on NSObject. Categories are an Objective-C feature much like extensions. The result is that the Swift compiler thinks that NSObject implements controlTextDidChange(:), therefore you need to “override” it.

You will see more about how this method ends up getting called in the Notifications chapter, section “For the More Curious: Delegates and Notifications”.