Clifton Labrum Clifton Labrum - 3 months ago 64
iOS Question

NotificationCenter Crash in Swift 3

Is it just me, or did

become a hot mess in Swift 3? :) I have the following setup:

extension Notification.Name {
static let preferenceNotification = Notification.Name("preferencesChanged")

//I fire the notification elsewhere like this: .preferenceNotification, object: nil)

In my first view controller, this works great:

//View Controller A <-- Success!
NotificationCenter.default.addObserver(self, selector: #selector(refreshData), name: .preferenceNotification, object: nil)

func refreshData(){

But this view controller:

//View Controller B <-- Crash :(
NotificationCenter.default.addObserver(self, selector: #selector(loadEntries(search:)), name: .preferenceNotification, object: nil)

func loadEntries(search:String?){

...crashes with:

[NSConcreteNotification length]: unrecognized selector sent to instance

As far as I can tell, my observer is set up correctly. Any idea what I'm doing wrong?


Your issue is with your loadEntries(search:) method. It's not a valid signature. The selector used with Notification Center must either have no parameters or just one parameter. And if you have one parameter, that parameter will be the Notification object, not the notification name.

Your loadEntries needs to be:

func loadEntries(_ notification: NSNotification) {
    // Optional check of the name
    if == .preferenceNotification {

And the selector would need to be: