0

Im learning notification centers right now and am getting this error while trying to register an observer: Cannot convert value of type 'Selector' to expected argument type 'String'

My observer code:

NotificationCenter.addObserver(self, forKeyPath: #selector(receivedMsg), options: Notification.Name("NC1"), context: nil)

Function receivedMsg:

 @objc func receivedMsg() {
print("MSG Received")
}

Working off this tutorial: https://www.hackingwithswift.com/example-code/system/how-to-post-messages-using-notificationcenter

Why am I getting this error and what can I do to fix it? (Swift 4.2)

  • You are using the wrong method for adding observer to Notification Center. There is no `forKeyPath:` argument in the method signature for the observer adding in Notification Center. Use the correct method signature [addObserver(_:selector:name:object:)](https://developer.apple.com/documentation/foundation/notificationcenter/1415360-addobserver) – nayem Feb 07 '19 at 03:45

3 Answers3

0

You're using the wrong method to add as an observer. You want to use this instead: NotificationCenter.default.addObserver(self, selector: #selector(receivedMsg), name: Notification.Name("NS1"), object: nil)

AdamPro13
  • 7,232
  • 2
  • 30
  • 28
0

You'll need to fix two things:

  1. Access an instance of NotificationCenter with NotificationCenter.default

  2. Use the addObserver method signature available on NotificationCenter

Complete code should be something like

NotificationCenter.default.addObserver(self, selector: #selector(receivedMsg), name: Notification.Name("NC1"), object: nil)
Rob MacEachern
  • 821
  • 8
  • 13
0
NotificationCenter.default.addObserver(self, selector: #selector(receivedMsg), name: Notification.Name("NC1"), object: nil)

then implement

@objc func receivedMsg() {
    print("MSG Received")
}

Keypath is used for KVO notification

The biggest difference between KVO and NotificationCenter is that KVO tracks specific changes to an object, while NotificationCenter is used to track generic events, like when a button is pressed to post an action.

may get details in this link

Ankur Lahiry
  • 2,253
  • 1
  • 15
  • 25