Observer

suggest change

The observer pattern is where an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems. The Observer pattern is also a key part in the familiar model–view–controller (MVC) architectural pattern. Wikipedia

The observer pattern fits when one object needs to notify observers of behavior or state changes.

First, create a reference to the notification center:

let notifCentre = NotificationCenter.default

That reference can be used from anywhere. Register an observer with a Notification.Name. A string is not the type of the name parameter. The selector must match an @objc method on a class that inherits from NSObject:

notifCentre.addObserver(self, selector: #selector(myFunc), name: Notification.Name("myNotification"), object: nil)

This registers for "myNotification" and calls myFunc when that notification is posted. The method belongs on the same object:

@objc func myFunc() {
    print("The notification has been received")
}

One of the advantages to this pattern is that you can add many classes as observers and thus perform many actions after one notification.

The notification can be posted from almost anywhere:

notifCentre.post(name: Notification.Name("myNotification"), object: nil)

Extra information goes in the userInfo dictionary, not in object.

let myInfo = "pass this on"
notifCentre.post(name: Notification.Name("myNotification"), object: nil, userInfo: ["moreInfo": myInfo])

The method then needs a Notification parameter, and the selector registered above must be #selector(myFunc(_:)) so it matches:

@objc func myFunc(_ notification: Notification) {
    let userInfo = notification.userInfo as? [String: Any]
    let passedInfo = userInfo?["moreInfo"] as? String ?? ""
    print("The notification \(passedInfo) has been received")
    // The notification pass this on has been received
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents