Search code examples
iosswiftnsnotificationcenternsnotification

Do I need to add observer if I have a func to take NSNotification as parameter


Just like the question title

for say I have code like

func receieveNotification(notification : NSNotification) {

    ......verify notification
    ......retrieve userInfo

}

Do I still need to add observer to NSNotificationCenter.defaultCenter() ? If I do. How to?


Solution

  • An NSNotification is sent when some object calls the post method on an NSNotificationCenter. The notification center then calls the designated receiving method on each object that has been registered with it.

    If you do not register with a notification center, then there is no way for the system to know that it should send the notification to you. Although there can be other registration centers, in iOS you will almost always use the default.

    When you register for a notification, you specify which object is to receive the notification, what method on that object to call, which notification you are registering for, and what sender you want to receive notifications from. If you want to receive every one of a particular kind of notification (that is, you don't care which object sent it), you can specify nil for the sender.

    Thus, to register for the notification, "MyNotification", and you don't care what object sent it, you call the following:

    NSNotificationCenter.defaultCenter().addObserver(self, "gestureHandler", "MyNotification", nil)
    

    Where to place this call depends on when you want this object to listen for it. For example, if the receiver is a UIView, you probably want to register when the view is about to be shown, not when the view is created.

    It is extremely important that you unregister when you want to stop receiving notifications, such as when the receiver goes out of scope. You do this by calling 'removeObserver()`.

    You should search through Xcode's documentation and read the Notification Programming Topics.