addObserver(forName:object:queue:using:)
Adds an entry to the notification center to receive notifications that passed to the provided block.
Declaration
func addObserver(forName name: NSNotification.Name?, object obj: Any?, queue: OperationQueue?, using block: @escaping @Sendable (Notification) -> Void) -> any NSObjectProtocolParameters
- name:
The name of the notification to register for delivery to the observer block. Specify a notification name to deliver only entries with this notification name.
When
nil, the sender doesn’t use notification names as criteria for delivery. - obj:
The object that sends notifications to the observer block. Specify a sender to deliver only notifications from this sender.
When
nil, the notification center doesn’t use the sender as criteria for the delivery. - queue:
The operation queue where the
blockruns.When
nil, the block runs synchronously on the posting thread. - block:
The block that executes when receiving a notification.
The notification center copies the block. The notification center strongly holds the copied block until you remove the observer registration.
The block takes one argument: the notification.
Return Value
An opaque object to act as the observer. Notification center strongly holds this return value until you remove the observer registration.
Discussion
If a notification triggers more than one observer block, the blocks can all execute concurrently (but on their queue or on the current thread).
The following example shows how you can register to receive locale change notifications. It stores the return value from addObserver(forName:object:queue:using:) in an instance property called localeChangeObserver.
Unregister an observer to stop receiving notifications. To unregister an observer, use NotificationCenter/removeObserver(_:) or removeObserver(_:name:object:) with the most specific detail possible. For example, if you used a name and object to register the observer, use the name and object to remove it.
You must invoke NotificationCenter/removeObserver(_:) or removeObserver(_:name:object:) before the system deallocates any object that addObserver(forName:object:queue:using:) specifies.
Another common practice is to create a one-time notification by removing the observer from within the observation block, as in the following example.
This example stores the opaque observer object in an instance property called token, which you can use to remove the observer prior to receiving the notification.