Skip to content

Instantly share code, notes, and snippets.

@mdb1
Created August 12, 2023 23:17
Show Gist options
  • Save mdb1/770bf255a64529b99eaac1208f89b8a2 to your computer and use it in GitHub Desktop.
Save mdb1/770bf255a64529b99eaac1208f89b8a2 to your computer and use it in GitHub Desktop.
Notification Center Observer protocol
/// Reflects notification observer functionality of `NotificationCenter`.
public protocol NotificationObserverProtocol: AnyObject {
/// Adds an entry to the notification center to call the provided selector with the notification.
/// - Parameters:
/// - observer: An object to register as an observer.
/// - aSelector: A selector that specifies the message the receiver sends observer to alert it to the notification
/// posting. The method that aSelector specifies must have one and only one argument
/// (an instance of NSNotification).
/// - aName: The name of the notification to register for delivery to the observer. Specify a notification name to
/// deliver only entries with this notification name.
/// When nil, the sender doesn’t use notification names as criteria for the delivery.
/// - anObject: The object that sends notifications to the observer. Specify a notification sender to deliver only
/// notifications from this sender.
/// When nil, the notification center doesn’t use sender names as criteria for delivery.
func addObserver(
_ observer: Any,
selector aSelector: Selector,
name aName: NSNotification.Name?,
object anObject: Any?
)
}
public extension NotificationObserverProtocol {
/// Adds an entry to the notification center to call the provided selector with the notification.
/// - Parameters:
/// - observer: An object to register as an observer.
/// - aSelector: A selector that specifies the message the receiver sends observer to alert it to the notification
/// posting. The method that aSelector specifies must have one and only one argument
/// (an instance of NSNotification).
/// - aName: The name of the notification to register for delivery to the observer. Specify a notification name to
/// deliver only entries with this notification name.
/// When nil, the sender doesn’t use notification names as criteria for the delivery.
func addObserver(
_ observer: Any,
selector aSelector: Selector,
name aName: NSNotification.Name?
) {
addObserver(observer, selector: aSelector, name: aName, object: nil)
}
}
extension NotificationCenter: NotificationObserverProtocol {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment