beeb
beeb

Reputation: 1217

Execute callback when text changes inside a NSTextField in Swift

I have a NSTextField and I would like to execute a callback whenever the text inside it changes. The callback would be to enable a disabled "save" button at the bottom of the form.

What I managed to do so far is sub-class NSTextView in order to override textDidChange(notification)

import Cocoa

class MyTextField: NSTextField {

    override func textDidChange(notification: NSNotification) {
        super.textDidChange(notification)
    }

}

After that, I didn't manage to execute a function inside my ViewController. I tried using NSNotificationCenter to trigger some kind of global event that I could catch inside the ViewController like so :

//MyTextField.swift

import Cocoa

class MyTextField: NSTextField {

    override func textDidChange(notification: NSNotification) {
        NSNotificationCenter.defaultCenter().postNotification(notification)
        super.textDidChange(notification)
    }

}


//ViewController.swift

import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "fieldTextDidChange:", name: "NSTextDidChangeNotification", object: nil)
    }
    override func viewDidAppear() {
        super.viewDidAppear()
    }

    func fieldTextDidChange(notification: NSNotification) {
        print(notification, appendNewline: true)
    }
}

But I get a runtime error when typing inside the field : Thread 1: EXC_BAD_ACCESS (code=2, address=0x7fff5f3fff70) on the line that calls postNotification()

How can I manage to trigger a callback on text change of a NSTextField ?

EDIT

Sub-classing and sending a notification is silly as pointed out by matt. There is no need to sub-class the text field. Simply observing the NSTextDidChangeNotification is enough to react to the event I was looking for. I had tested this but I was missing a colon at the end of the selector on top of this, so I thought it was not the correct method. It is indeed the correct method.

Upvotes: 0

Views: 2741

Answers (1)

matt
matt

Reputation: 534885

The reason you are crashing is that your selector is wrong. It should be selector: "fieldTextDidChange:" (notice the final colon).

Upvotes: 1

Related Questions