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.)
#selector
, the compiler would've pointed out the problem –sayHello
needs to be@objc
. Compare https://mcmap.net/q/23779/-how-can-i-deal-with-objc-inference-deprecation-with-selector-in-swift-4/2976878 – Tenderhearted#selector(yourVC.yourfunctionName)
– Phoneme#selector(sayHello)
and your method signature you should also pass the notification object (drop the NS prefix)@objc func sayHello(_ notification: Notification)
– Samsunself
instead ofviewControllerName
. Example:#selector(self.functionName)
– Phoneme