NSNotificationCenter Example in Swift

By | July 15, 2015

Here is a simple demo on how to use “NSNotificationCenter” in swift.

NSNotificationCenter is particularly useful when there are multiple class or struct instances that need to take action based on something that happens elsewhere in your application.

To Register the notification… we will call

 NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateOnNotification", name: notificationKey, object: nil)

Now to trigger the notification…

 @IBAction func broadcastNotification(sender: UIButton){
    NSNotificationCenter.defaultCenter().postNotificationName(notificationKey, object: self)
}

//This will be triggered once the notification is sent.
func updateOnNotification() {
    println("Notification Sent");
}

The “notificationKey” should be unique for each notification to identify different broadcasts.

for eg : let notificationKey = “notification_key”

IMPORTANT NOTE : A notification observer will be removed once you close a ViewController in which it is added. i.e an observer will be removed once dealloc is called from a ViewController. In Swift it is by default.

Please leave your valuable comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *