addObserver :selector:name:object:
Adds an entry to the receiver’s dispatch table with an observer, a notification selector and optional criteria: notification name and sender.
- (void)addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString*)notificationName object:(id)notificationSender
Parameters
- notificationObserver
- Object registering as an observer. This value must not be
nil
. - notificationSelector
- Selector that specifies the message the receiver sends notificationObserver to notify it of the notification posting. The method specified by notificationSelector must have one and only one argument (an instance of
NSNotification
).[NSNotificationCenter addObserver] - notificationName
- The name of the notification for which to register the observer; that is, only notifications with this name are delivered to the observer.If you pass
nil
, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer. - notificationSender
- The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer.If you pass
nil
, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.
Discussion
Be sure to invoke
removeObserver:
or removeObserver:name:object:
before notificationObserver or any object specified in addObserver :selector:name:object:
is deallocated.
Example of [NSNotificationCenter addObserver]
@implementation TestClass
- (void) dealloc
{
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (id) init
{
self = [super init];
if (!self) return nil;
// Add this instance of TestClass as an observer of the TestNotification.
// We tell the notification center to inform us of "TestNotification"
// notifications using the receiveTestNotification: selector. By
// specifying object:nil, we tell the notification center that we are not
// interested in who posted the notification. If you provided an actual
// object rather than nil, the notification center will only notify you
// when the notification was posted by that particular object.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:)
name:@"TestNotification"
object:nil];
return self;
}
- (void) receiveTestNotification:(NSNotification *) notification
{
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.
if ([[notification name] isEqualToString:@"TestNotification"])
NSLog (@"Successfully received the test notification!");
}
@end