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.)
addObserver(forName:object:queue:using:) Adds an entry to the notification center to receive notifications that passed to the provided block.
default — This is the notification variable you can create it globally inside your class if you having more notifications. addObserver(self, — This is for the class where we are going to observer notification.
An object containing information broadcast to registered observers that bridges to Notification ; use NSNotification when you need reference semantics or other Foundation-specific behavior.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With