For a MacOS app I'm building with Xcode/Swift, I'm trying to call a function when the value has changed in a NSTextField (while the user is typing). So I've added a notification center observer:
import Cocoa
class ViewController: NSViewController, NSTextDelegate {
@IBOutlet weak var textField: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(textFieldDidChange(_:)), name: Notification.Name.NSTextDidChange, object: nil)
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func textFieldDidChange(_ notification: Notification) {
print(textField.stringValue)
}
}
This works fine. But now I want it to apply to a specific NSTextField, so I set the object in the observer:
NotificationCenter.default.addObserver(self, selector: #selector(textFieldDidChange(_:)), name: Notification.Name.NSTextDidChange, object: textField)
Now it suddenly doesn't work anymore, and I can't seem to figure out why. Just starting out with Xcode and Swift. I've been searching for a solution all weekend, but most answers I find apply to iOS apps, older versions of swift, Objective-C etc.