Search code examples
swiftnsnotificationcenterxcode9addobserver

Swift 4 - Notification Center addObserver issue


I'm crashing and getting an unrecognized selector error every time a Notification arrives and the App tries to execute its associated method. Here's my code - which is in viewDidLoad:

let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: Selector(("sayHello")), name:NSNotification.Name(rawValue: "dataDownloadCompleted"), object: nil)

The sayHello() method is quite simple - looks like this:

func sayHello() {
    print("Hello")
}

I've verified that the Notification is posted successfully and that it arrives successfully - so that's not the issue. The crash happens when the App looks to act upon the arrival of the Notification - by executing the sayHello() method. It keeps giving me that unrecognized selector error.

Any ideas what I'm doing wrong? (By the way, this worked perfectly with Swift 3 & Xcode 8, but now with Swift 4 and Xcode 9 the syntax has changed [Xcode walked me through the necessary code fixes/updates] - but the crashes keep happening.)


Solution

  • You can improve your code with these steps:

    extension Notification.Name {
        static let dataDownloadCompleted = Notification.Name(
           rawValue: "dataDownloadCompleted")
    }
    

    And use it like this:

    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self,
                                   selector: #selector(YourClass.sayHello),
                                   name: .dataDownloadCompleted,
                                   object: nil)
    

    But as was already pointed out, issue is solved by changing to #selector