An object containing information broadcast to registered observers that bridges to Notification
; use NSNotification
when you need reference semantics or other Foundation-specific behavior.
SDKs
- iOS 2.0+
- macOS 10.0+
- Mac Catalyst 13.0+
- tvOS 9.0+
- watchOS 2.0+
Framework
- Foundation
Declaration
class NSNotification : NSObject
Overview
A notification contains a name, an object, and an optional dictionary, and is broadcast to by instances of Notification
or Distributed
. The name is a tag identifying the notification. The object is any object that the poster of the notification wants to send to observers of that notification (typically, the object posting the notification). The dictionary stores other related objects, if any. NSNotification
objects are immutable.
You don’t usually create your own notifications directly, but instead call the Notification
methods post(name:
and post(name:
.
Important
The Swift overlay to the Foundation framework provides the Notification
structure, which bridges to the NSNotification
class. For more information about value types, see Working with Cocoa Frameworks in Using Swift with Cocoa and Objective-C (Swift 4.1).
Object Comparison
The objects of a notification are compared using pointer equality for local notifications. Distributed notifications use strings as their objects, and those strings are compared using is
, because pointer equality doesn’t make sense across process boundaries.
Creating Subclasses
You can subclass NSNotification
to contain information in addition to the notification name, object, and dictionary. This extra data must be agreed upon between notifiers and observers.
Notification
is a class cluster with no instance variables. As such, you must subclass NSNotification
and override the primitive methods name
, object
, and user
. You can choose any designated initializer you like, but be sure that your initializer does not call init()
on super
(NSNotification
is not meant to be instantiated directly, and its init
method raises an exception).