Junior
What is a notification center?
sobes.tech AI
Answer from AI
The Notification Center, or NotificationCenter, is a mechanism in Foundation that implements the "Observer" pattern. It allows objects to broadcast notifications to other objects that are subscribed to them.
Key components:
- Publisher: An object that posts a notification.
- Observer: An object that subscribes to and reacts to notifications.
- Notification: An object representing the event itself. It contains the notification name, sender, and an optional dictionary of user information.
Advantages:
- Loose coupling between objects.
- Convenient for broadcasting events to many subscribers.
Disadvantages:
- Debugging complexity due to indirect interaction.
- Potential issues with managing the lifecycle of observers if they are not properly removed.
Example of publishing and subscribing:
import Foundation
// Notification name
extension Notification.Name {
static let myCustomNotification = Notification.Name("myCustomNotification")
}
// Publisher
class Publisher {
func publishNotification() {
let userInfo: [AnyHashable: Any] = ["data": "some important data"]
NotificationCenter.default.post(name: .myCustomNotification, object: self, userInfo: userInfo)
print("Notification published")
}
}
// Observer
class Observer {
init() {
// Subscribe to notification
NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: .myCustomNotification, object: nil)
}
// Method called upon receiving notification
@objc func handleNotification(_ notification: Notification) {
print("Notification received!")
if let userInfo = notification.userInfo {
print("User Info: \(userInfo)")
}
}
deinit {
// Unsubscribe from notification upon deinitialization
NotificationCenter.default.removeObserver(self)
}
}
// Usage
let publisher = Publisher()
let observer = Observer()
publisher.publishNotification()