Sunteți pe pagina 1din 16

NSNotificationCenter Class Reference

Contents

NSNotificationCenter Class Reference 4


Overview 4 Tasks 6 Getting the Notification Center 6 Managing Notification Observers 7 Posting Notifications 7 Class Methods 7 defaultCenter 7 Instance Methods 8 addObserver:selector:name:object: 8 addObserverForName:object:queue:usingBlock: 9 postNotification: 11 postNotificationName:object: 11 postNotificationName:object:userInfo: 12 removeObserver: 13 removeObserver:name:object: 14

Document Revision History 15

2010-08-03 | 2010 Apple Inc. All Rights Reserved.

Tables

NSNotificationCenter Class Reference 4


Table 1 Table 2 Types of dispatch table entries 5 Example notification dispatch table 5

2010-08-03 | 2010 Apple Inc. All Rights Reserved.

NSNotificationCenter Class Reference

Inherits from Conforms to Framework Availability Companion guide Declared in Related sample code

NSObject NSObject (NSObject) /System/Library/Frameworks/Foundation.framework Available in iOS 2.0 and later. Notification Programming Topics NSNotification.h Audio Mixer (MixerHost) EADemo KeyboardAccessory SeismicXML SpeakHere

Overview
An NSNotificationCenter object (or simply, notification center) provides a mechanism for broadcasting information within a program. An NSNotificationCenter object is essentially a notification dispatch table. Objects register with a notification center to receive notifications (NSNotification objects) using the addObserver:selector:name:object: (page 8) or addObserverForName:object:queue:usingBlock: (page 9) methods. Each invocation of this method specifies a set of notifications. Therefore, objects may register as observers of different notification sets by calling these methods several times. When an object (known as the notification sender) posts a notification, it sends an NSNotification object to the notification center. The notification center then notifies any observers for which the notification meets the criteria specified on registration by sending them the specified notification message, passing the notification as the sole argument.

2010-08-03 | 2010 Apple Inc. All Rights Reserved.

NSNotificationCenter Class Reference Overview

A notification center maintains a notification dispatch table which specifies a notification set for a particular observer. A notification set is a subset of the notifications posted to the notification center. Each table entry contains three items:

Notification observer: Required. The object to be notified when qualifying notifications are posted to the notification center. Notification name: Optional. Specifying a name reduces the set of notifications the entry specifies to those that have this name. Notification sender: Optional. Specifying a sender reduces the set of notifications the entry specifies to those sent by this object.

Table 1 shows the four types of dispatch table entries and the notification sets they specify. (This table omits the always present notification observer.)
Table 1 Types of dispatch table entries Notification sender Notification set specified

Notification name

Specified

Specified

Notifications with a particular name from a specific sender. Notifications with a particular name by any sender. Notifications posted by a specific sender. All notifications.

Specified Unspecified Unspecified

Unspecified Specified Unspecified

Table 2 shows an example dispatch table with four observers.


Table 2 Observer observerA observerB observerC observerC observerD Example notification dispatch table Notification name NSFileHandleReadCompletionNotification nil NSWindowDidChangeScreenNotification nil nil Notification sender nil addressTableView documentWindow addressTableView nil

2010-08-03 | 2010 Apple Inc. All Rights Reserved.

NSNotificationCenter Class Reference Tasks

When notifications are posted to the notification center, each of the observers in Table 2 are notified of the following notifications:

observerA: Notifications named NSFileHandleReadCompletionNotification. observerB: Notifications sent by addressTableView. observerC: Notifications named NSWindowDidChangeScreenNotification sent by documentWindow

and notifications sent by addressTableView.

observerD: All notifications.

The order in which observers receive notifications is undefined. It is possible for the posting object and the observing object to be the same. A notification center delivers notifications to observers synchronously. In other words, the postNotification: (page 11) methods do not return until all observers have received and processed the notification. To send notifications asynchronously use NSNotificationQueue. In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself. Important The notification center does not retain its observers, therefore, you must ensure that you unregister observers (using removeObserver: (page 13) or removeObserver:name:object: (page 14)) before they are deallocated. (If you don't, you will generate a runtime error if the center sends a message to a freed object.) Each running Cocoa program has a default notification center. You typically dont create your own. An NSNotificationCenter object can deliver notifications only within a single program. If you want to post a notification to other processes or receive notifications from other processes, use a NSDistributedNotificationCenter object.

Tasks
Getting the Notification Center
+ defaultCenter

(page 7) Returns the processs default notification center.

2010-08-03 | 2010 Apple Inc. All Rights Reserved.

NSNotificationCenter Class Reference Class Methods

Managing Notification Observers


addObserver:selector:name:object:

(page 8) Adds an entry to the receivers dispatch table with an observer, a notification selector and optional criteria: notification name and sender. (page 9) Adds an entry to the receivers dispatch table with a notification queue and a block to add to the queue, and optional criteria: notification name and sender. (page 13) Removes all the entries specifying a given observer from the receivers dispatch table. (page 14) Removes matching entries from the receivers dispatch table.

addObserverForName:object:queue:usingBlock:

removeObserver:

removeObserver:name:object:

Posting Notifications
postNotification:

(page 11) Posts a given notification to the receiver. (page 11) Creates a notification with a given name and sender and posts it to the receiver. (page 12) Creates a notification with a given name, sender, and information and posts it to the receiver.

postNotificationName:object:

postNotificationName:object:userInfo:

Class Methods
defaultCenter
Returns the processs default notification center.
+ (id)defaultCenter

Return Value The current processs default notification center, which is used for system notifications. Availability Available in iOS 2.0 and later.
Related Sample Code Audio Mixer (MixerHost)

2010-08-03 | 2010 Apple Inc. All Rights Reserved.

NSNotificationCenter Class Reference Instance Methods

EADemo KeyboardAccessory SeismicXML SpeakHere

Declared in
NSNotification.h

Instance Methods
addObserver:selector:name:object:
Adds an entry to the receivers 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).
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 doesnt use a notifications 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 doesnt use a notifications sender to decide whether to deliver it to the observer.

2010-08-03 | 2010 Apple Inc. All Rights Reserved.

NSNotificationCenter Class Reference Instance Methods

Discussion Be sure to invoke removeObserver: (page 13) or removeObserver:name:object: (page 14) before notificationObserver or any object specified in addObserver:selector:name:object: is deallocated. Availability Available in iOS 2.0 and later. See Also
addObserverForName:object:queue:usingBlock: removeObserver:

(page 9)

(page 13)

Related Sample Code AddMusic EADemo KeyboardAccessory SimpleUndo SpeakHere

Declared in
NSNotification.h

addObserverForName:object:queue:usingBlock:
Adds an entry to the receivers dispatch table with a notification queue and a block to add to the queue, and optional criteria: notification name and sender.
- (id)addObserverForName:(NSString *)name

object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *))block

Parameters
name

The name of the notification for which to register the observer; that is, only notifications with this name are used to add the block to the operation queue. If you pass nil, the notification center doesnt use a notifications name to decide whether to add the block to the operation queue.
obj

The object whose notifications you want to add the block to the operation queue. If you pass nil, the notification center doesnt use a notifications sender to decide whether to add the block to the operation queue.

2010-08-03 | 2010 Apple Inc. All Rights Reserved.

NSNotificationCenter Class Reference Instance Methods

queue

The operation queue to which block should be added. If you pass nil, the block is run synchronously on the posting thread.
block

The block to be executed when the notification is received. The block is copied by the notification center and (the copy) held until the observer registration is removed. The block takes one argument: notification The notification. Return Value An opaque object to act as the observer. Discussion To unregister observations, you pass the object returned by this method to removeObserver: (page 13). You must invoke removeObserver: (page 13) or removeObserver:name:object: (page 14) before any object specified by addObserverForName:object:queue:usingBlock: is deallocated. If a given notification triggers more than one observer block, the blocks may all be executed concurrently with respect to one another (but on their given queue or on the current thread). Special Considerations In a garbage collected environment, the system does not keep a reference to observers, and registrations are automatically cleaned up when an observer is collected. You therefore need to ensure that the observer object is not collected for as long as you want the notification registration to remain. You must either:
1.

Maintain a strong reference to the returned observer object somewhere (for example in an instance variable or in a global variable). You typically do this if you intend to explicitly call removeObserver: (page 13) on it at some point.

2.

Retain the object (using CFRetain). You would do this if you intend to never remove the observer.

(In a reference counted environment, the system retains the returned observer object until it is removed, so there is no need to retain it yourself.) Availability Available in iOS 4.0 and later.

2010-08-03 | 2010 Apple Inc. All Rights Reserved.

10

NSNotificationCenter Class Reference Instance Methods

See Also
addObserver:selector:name:object: removeObserver:

(page 8)

(page 13)

Declared in
NSNotification.h

postNotification:
Posts a given notification to the receiver.
- (void)postNotification:(NSNotification *)notification

Parameters
notification

The notification to post. This value must not be nil. Discussion You can create a notification with the NSNotification class method notificationWithName:object: or notificationWithName:object:userInfo:. An exception is raised if notification is nil. Availability Available in iOS 2.0 and later. See Also
postNotificationName:object:

(page 11) (page 12)

postNotificationName:object:userInfo:

Declared in
NSNotification.h

postNotificationName:object:
Creates a notification with a given name and sender and posts it to the receiver.
- (void)postNotificationName:(NSString *)notificationName

object:(id)notificationSender

Parameters
notificationName

The name of the notification.

2010-08-03 | 2010 Apple Inc. All Rights Reserved.

11

NSNotificationCenter Class Reference Instance Methods

notificationSender

The object posting the notification. Discussion This method invokes postNotificationName:object:userInfo: (page 12) with a userInfo argument of nil. Availability Available in iOS 2.0 and later. See Also
postNotification:

(page 11)

Related Sample Code Audio Mixer (MixerHost) GLPaint HeadsUpUI Reachability SpeakHere

Declared in
NSNotification.h

postNotificationName:object:userInfo:
Creates a notification with a given name, sender, and information and posts it to the receiver.
- (void)postNotificationName:(NSString *)notificationName

object:(id)notificationSender userInfo:(NSDictionary *)userInfo

Parameters
notificationName

The name of the notification.


notificationSender

The object posting the notification.


userInfo

Information about the the notification. May be nil. Discussion This method is the preferred method for posting notifications.

2010-08-03 | 2010 Apple Inc. All Rights Reserved.

12

NSNotificationCenter Class Reference Instance Methods

Availability Available in iOS 2.0 and later. See Also


postNotificationName:object:

(page 11)

Related Sample Code EADemo SeismicXML

Declared in
NSNotification.h

removeObserver:
Removes all the entries specifying a given observer from the receivers dispatch table.
- (void)removeObserver:(id)notificationObserver

Parameters
notificationObserver

The observer to remove. Must not be nil. Discussion Be sure to invoke this method (or removeObserver:name:object: (page 14)) before notificationObserver or any object specified in addObserver:selector:name:object: (page 8) is deallocated. The following example illustrates how to unregister someObserver for all notifications for which it had previously registered:
[[NSNotificationCenter defaultCenter] removeObserver:someObserver];

Availability Available in iOS 2.0 and later. See Also


removeObserver:name:object:

(page 14)

Related Sample Code AlternateViews SimpleUndo

Declared in
NSNotification.h

2010-08-03 | 2010 Apple Inc. All Rights Reserved.

13

NSNotificationCenter Class Reference Instance Methods

removeObserver:name:object:
Removes matching entries from the receivers dispatch table.
- (void)removeObserver:(id)notificationObserver name:(NSString *)notificationName

object:(id)notificationSender

Parameters
notificationObserver

Observer to remove from the dispatch table. Specify an observer to remove only entries for this observer. Must not be nil, or message will have no effect.
notificationName

Name of the notification to remove from dispatch table. Specify a notification name to remove only entries that specify this notification name. When nil, the receiver does not use notification names as criteria for removal.
notificationSender

Sender to remove from the dispatch table. Specify a notification sender to remove only entries that specify this sender. When nil, the receiver does not use notification senders as criteria for removal. Discussion Be sure to invoke this method (or removeObserver: (page 13)) before the observer object or any object specified in addObserver:selector:name:object: (page 8) is deallocated. Availability Available in iOS 2.0 and later. See Also
removeObserver:

(page 13)

Related Sample Code AddMusic AppPrefs Audio Mixer (MixerHost) EADemo KeyboardAccessory

Declared in
NSNotification.h

2010-08-03 | 2010 Apple Inc. All Rights Reserved.

14

Document Revision History

This table describes the changes to NSNotificationCenter Class Reference .

Date 2010-08-03 2010-06-22

Notes Clarified discussion of addObserverForName:object:queue:usingBlock:. Corrected description of memory management behavior and removing the observer for addObserverForName:object:queue:usingBlock:. Modified the addObserverForName:object:usingBlock: description to extend return explanation and added release notes. Corrected method heading for addObserverForName:object:queue:usingBlock:. Added trailing colon. Added addObserverForName:object:queue:usingBlock: method. Updated for Mac OS X v10.6. Removed a statement that the observer parameter can be nil in the removeObserver:name:object: method. Updated for Mac OS X v10.5 Clarified how a notification center manages observers in its dispatch table. Updated return type of defaultCenter (page 7).

2010-04-29

2009-09-01

2009-08-28 2009-05-15 2008-07-11

2007-04-02 2006-11-07

2006-05-23

First publication of this content as a separate document.

2010-08-03 | 2010 Apple Inc. All Rights Reserved.

15

Apple Inc. 2010 Apple Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer for personal use only and to print copies of documentation for personal use provided that the documentation contains Apples copyright notice. The Apple logo is a trademark of Apple Inc. No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the technology described in this document. This document is intended to assist application developers to develop applications only for Apple-labeled computers. Apple Inc. 1 Infinite Loop Cupertino, CA 95014 408-996-1010 Apple, the Apple logo, Cocoa, Mac, Mac OS, and OS X are trademarks of Apple Inc., registered in the United States and other countries. IOS is a trademark or registered trademark of Cisco in the U.S. and other countries and is used under license.
Even though Apple has reviewed this document, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS DOCUMENT IS PROVIDED AS IS, AND YOU, THE READER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY. IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages. THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make any modification, extension, or addition to this warranty. Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state.

S-ar putea să vă placă și