Using NSNotificationCenter in Swift
/I'm working on a full post for later this week, but as I sat down to write some code this afternoon, I needed to implement an NSNotification observer on a text field (namely, UITextFieldTextDidChangeNotification) and stopped for a moment to think about whether I should implement it the same way I would have in Objective-C, or if their was a more Swift way of doing things.
My initial thought was to use my go-to method for notifications,
addObserver:selector:name:object:
but that looked like this:
let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver( self, selector: "textFieldTextChanged:", name:UITextFieldTextDidChangeNotification, object: nil ) func textFieldTextChanged(sender : AnyObject) { sendButton.enabled = messageField.text.utf16count > 0 }
and the thought of typing out a selector name in an un-checked string scares the U+1F4A9/U+E05A out of me, so I decided on the method I'm less familiar with, but the block based approach of addObserverForName:object:queue:usingBlock:
seemed much more in-line with where I want to be thinking as a Swift developer.
let notificationCenter = NSNotificationCenter.defaultCenter() let mainQueue = NSOperationQueue.mainQueue() var observer = notificationCenter.addObserverForName(UITextFieldTextDidChangeNotification, object: nil, queue: mainQueue) { _ in self.sendButton.enabled = self.messageField.text.utf16count > 0 }
Now I'm no longer dependent on spelling the selector correctly, and I'm writing trailing closures rather than transposing the Objective-C way of doing things to a new Swift context.
Prefer one over the other? Leave a comment and keep the discussion going.