Custom Notifications in Swift

September 8th, 2017

Filed under: Cocoa, Mac Development | Be the first to comment!

Notifications allow an object of one class to send a message for an object of another class to handle so the two classes don’t have to know about each other. The Cocoa framework has dozens of notifications, but you can also create your own.

Using custom notifications involves the following steps:

  • Get the notification center
  • Post the notification
  • Observe the notification
  • Handle the notification

Getting the Notification Center

The notification center is where you post and observe notifications. Each Cocoa application has its own notification center. Use the NotificationCenter class’s default property to access your application’s notification center.

let center = NotificationCenter.default

Posting a Notification

Call the NotificationCenter class’s post function to post a notification. Supply the name of the notification and an optional object if you need to pass data to the notification observer.

center.post(name: NSNotification.Name(rawValue: "NotificationName"), object: nil)

Notice that the notification name is a string. You may want to create an enumeration for your application’s custom notifications to avoid mistyping a notification name.

Observing a Notification

Call the NotificationCenter class’s addObserver function to observe a notification. The addObserver function takes the following arguments:

  • The observing object, which is usually self.
  • The selector, which contains the name of the function to call when receiving a notification.
  • The name of the notification to observe. The name must match the name you supplied to the post function.
  • The sender. If you want to observe all instances of the notification, use nil as the sender. If you want to observe notifications posted by a specific object, supply the object as the sender.

The following example demonstrates observing a notification:

center.addObserver(self, 
    selector: #selector(MyClass.handleNotification(_:)), 
    name: NSNotification.Name(rawValue: "NotificationName"), 
    object: nil)

Handling a Notification

Handling a notification involves writing a function. Functions that handle notifications take a NSNotification object as an argument.

func handleNotification(_ note: NSNotification) {

}

The argument for the function must match the argument for the selector when observing the notification. I put the _ character before the note argument so I wouldn’t have to supply an argument to the selector. If I didn’t have the _ character, I would have to supply the note argument to the selector when observing the notification.

#selector(MyClass.handleNotification(note:))
Facebooktwittergoogle_plusredditmail

Tags:


Leave a Reply

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