+ All Categories
Home > Documents > NSNotificationCenter Class

NSNotificationCenter Class

Date post: 08-Sep-2014
Category:
Upload: salik-siddiqui
View: 60 times
Download: 2 times
Share this document with a friend
Popular Tags:
16
NSNotificationCenter Class Reference
Transcript
Page 1: NSNotificationCenter Class

NSNotificationCenter Class Reference

Page 2: NSNotificationCenter Class

Contents

NSNotificationCenter Class Reference 4Overview 4Tasks 6

Getting the Notification Center 6Managing Notification Observers 7Posting Notifications 7

Class Methods 7defaultCenter 7

Instance Methods 8addObserver:selector:name:object: 8addObserverForName:object:queue:usingBlock: 9postNotification: 11postNotificationName:object: 11postNotificationName:object:userInfo: 12removeObserver: 13removeObserver:name:object: 14

Document Revision History 15

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

2

Page 3: NSNotificationCenter Class

Tables

NSNotificationCenter Class Reference 4Table 1 Types of dispatch table entries 5Table 2 Example notification dispatch table 5

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

3

Page 4: NSNotificationCenter Class

Inherits from NSObject

Conforms to NSObject (NSObject)

Framework /System/Library/Frameworks/Foundation.framework

Availability Available in iOS 2.0 and later.

Companion guide Notification Programming Topics

Declared in NSNotification.h

Related sample code Audio Mixer (MixerHost)

EADemo

KeyboardAccessory

SeismicXML

SpeakHere

OverviewAn NSNotificationCenter object (or simply, notification center) provides a mechanism for broadcastinginformation within a program. An NSNotificationCenter object is essentially a notification dispatch table.

Objects register with a notification center to receive notifications (NSNotification objects) using theaddObserver: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 asobservers 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 objectto the notification center. The notification center then notifies any observers for which the notification meetsthe criteria specified on registration by sending them the specified notification message, passing the notificationas the sole argument.

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

4

NSNotificationCenter Class Reference

Page 5: NSNotificationCenter Class

A notification center maintains a notification dispatch table which specifies a notification set for a particularobserver. A notification set is a subset of the notifications posted to the notification center. Each table entrycontains three items:

● Notification observer: Required. The object to be notified when qualifying notifications are posted to thenotification center.

● Notification name: Optional. Specifying a name reduces the set of notifications the entry specifies tothose that have this name.

● Notification sender: Optional. Specifying a sender reduces the set of notifications the entry specifies tothose sent by this object.

Table 1 shows the four types of dispatch table entries and the notification sets they specify. (This table omitsthe always present notification observer.)

Table 1 Types of dispatch table entries

Notification set specifiedNotification senderNotification name

Notifications with a particular name from a specificsender.

SpecifiedSpecified

Notifications with a particular name by any sender.UnspecifiedSpecified

Notifications posted by a specific sender.SpecifiedUnspecified

All notifications.UnspecifiedUnspecified

Table 2 shows an example dispatch table with four observers.

Table 2 Example notification dispatch table

Notification senderNotification nameObserver

nilNSFileHandleReadCompletionNotificationobserverA

addressTableViewnilobserverB

documentWindowNSWindowDidChangeScreenNotificationobserverC

addressTableViewnilobserverC

nilnilobserverD

NSNotificationCenter Class ReferenceOverview

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

5

Page 6: NSNotificationCenter Class

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

● observerA: Notifications named NSFileHandleReadCompletionNotification.

● observerB: Notifications sent by addressTableView.

● observerC: Notifications namedNSWindowDidChangeScreenNotification sent bydocumentWindowand notifications sent by addressTableView.

● observerD: All notifications.

The order in which observers receive notifications is undefined. It is possible for the posting object and theobserving object to be the same.

A notification center delivers notifications to observers synchronously. In other words, thepostNotification: (page 11) methods do not return until all observers have received and processed thenotification. 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 thesame thread in which an observer registered itself.

Important The notification center does not retain its observers, therefore, you must ensure that youunregister observers (using removeObserver: (page 13) or removeObserver:name:object: (page 14)) beforethey are deallocated. (If you don't, you will generate a runtime error if the center sends a message to a freedobject.)

Each running Cocoa program has a default notification center. You typically don’t create your own. AnNSNotificationCenter object can deliver notifications only within a single program. If you want to post anotification to other processes or receive notifications from other processes, use aNSDistributedNotificationCenter object.

Tasks

Getting the Notification Center

+ defaultCenter (page 7)Returns the process’s default notification center.

NSNotificationCenter Class ReferenceTasks

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

6

Page 7: NSNotificationCenter Class

Managing Notification Observers

– addObserver:selector:name:object: (page 8)Adds an entry to the receiver’s dispatch table with an observer, a notification selector and optional criteria:notification name and sender.

– addObserverForName:object:queue:usingBlock: (page 9)Adds an entry to the receiver’s dispatch table with a notification queue and a block to add to the queue,and optional criteria: notification name and sender.

– removeObserver: (page 13)Removes all the entries specifying a given observer from the receiver’s dispatch table.

– removeObserver:name:object: (page 14)Removes matching entries from the receiver’s dispatch table.

Posting Notifications

– postNotification: (page 11)Posts a given notification to the receiver.

– postNotificationName:object: (page 11)Creates a notification with a given name and sender and posts it to the receiver.

– postNotificationName:object:userInfo: (page 12)Creates a notification with a given name, sender, and information and posts it to the receiver.

Class Methods

defaultCenter

Returns the process’s default notification center.

+ (id)defaultCenter

Return ValueThe current process’s default notification center, which is used for system notifications.

AvailabilityAvailable in iOS 2.0 and later.

Related Sample CodeAudio Mixer (MixerHost)

NSNotificationCenter Class ReferenceClass Methods

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

7

Page 8: NSNotificationCenter Class

EADemoKeyboardAccessorySeismicXMLSpeakHere

Declared inNSNotification.h

Instance Methods

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)notificationSelectorname:(NSString *)notificationName object:(id)notificationSender

ParametersnotificationObserver

Object registering as an observer. This value must not be nil.

notificationSelectorSelector that specifies the message the receiver sends notificationObserver to notify it of thenotification posting. The method specified by notificationSelector must have one and only oneargument (an instance of NSNotification).

notificationNameThe name of the notification for which to register the observer; that is, only notifications with this nameare delivered to the observer.

If you pass nil, the notification center doesn’t use a notification’s name to decide whether to deliver itto the observer.

notificationSenderThe object whose notifications the observer wants to receive; that is, only notifications sent by this senderare delivered to the observer.

If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to deliverit to the observer.

NSNotificationCenter Class ReferenceInstance Methods

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

8

Page 9: NSNotificationCenter Class

DiscussionBe sure to invoke removeObserver: (page 13) or removeObserver:name:object: (page 14) beforenotificationObserver or any object specified in addObserver:selector:name:object: is deallocated.

AvailabilityAvailable in iOS 2.0 and later.

See Also– addObserverForName:object:queue:usingBlock: (page 9)– removeObserver: (page 13)

Related Sample CodeAddMusicEADemoKeyboardAccessorySimpleUndoSpeakHere

Declared inNSNotification.h

addObserverForName:object:queue:usingBlock:

Adds an entry to the receiver’s dispatch table with a notification queue and a block to add to the queue, andoptional criteria: notification name and sender.

- (id)addObserverForName:(NSString *)nameobject:(id)objqueue:(NSOperationQueue *)queueusingBlock:(void (^)(NSNotification *))block

Parametersname

The name of the notification for which to register the observer; that is, only notifications with this nameare used to add the block to the operation queue.

If you pass nil, the notification center doesn’t use a notification’s name to decide whether to add theblock to the operation queue.

objThe object whose notifications you want to add the block to the operation queue.

If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to add theblock to the operation queue.

NSNotificationCenter Class ReferenceInstance Methods

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

9

Page 10: NSNotificationCenter Class

queueThe operation queue to which block should be added.

If you pass nil, the block is run synchronously on the posting thread.

blockThe 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 ValueAn opaque object to act as the observer.

DiscussionTo unregister observations, you pass the object returned by this method to removeObserver: (page 13). Youmust invoke removeObserver: (page 13) or removeObserver:name:object: (page 14) before any objectspecified by addObserverForName:object:queue:usingBlock: is deallocated.

If a given notification triggers more than one observer block, the blocks may all be executed concurrently withrespect to one another (but on their given queue or on the current thread).

Special ConsiderationsIn a garbage collected environment, the system does not keep a reference to observers, and registrations areautomatically cleaned up when an observer is collected. You therefore need to ensure that the observer objectis 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 variableor 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, sothere is no need to retain it yourself.)

AvailabilityAvailable in iOS 4.0 and later.

NSNotificationCenter Class ReferenceInstance Methods

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

10

Page 11: NSNotificationCenter Class

See Also– addObserver:selector:name:object: (page 8)– removeObserver: (page 13)

Declared inNSNotification.h

postNotification:

Posts a given notification to the receiver.

- (void)postNotification:(NSNotification *)notification

Parametersnotification

The notification to post. This value must not be nil.

DiscussionYou can create a notification with the NSNotification class method notificationWithName:object:or notificationWithName:object:userInfo:. An exception is raised if notification is nil.

AvailabilityAvailable in iOS 2.0 and later.

See Also– postNotificationName:object: (page 11)– postNotificationName:object:userInfo: (page 12)

Declared inNSNotification.h

postNotificationName:object:

Creates a notification with a given name and sender and posts it to the receiver.

- (void)postNotificationName:(NSString *)notificationNameobject:(id)notificationSender

ParametersnotificationName

The name of the notification.

NSNotificationCenter Class ReferenceInstance Methods

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

11

Page 12: NSNotificationCenter Class

notificationSenderThe object posting the notification.

DiscussionThis method invokes postNotificationName:object:userInfo: (page 12) with a userInfo argument ofnil.

AvailabilityAvailable in iOS 2.0 and later.

See Also– postNotification: (page 11)

Related Sample CodeAudio Mixer (MixerHost)GLPaintHeadsUpUIReachabilitySpeakHere

Declared inNSNotification.h

postNotificationName:object:userInfo:

Creates a notification with a given name, sender, and information and posts it to the receiver.

- (void)postNotificationName:(NSString *)notificationNameobject:(id)notificationSender userInfo:(NSDictionary *)userInfo

ParametersnotificationName

The name of the notification.

notificationSenderThe object posting the notification.

userInfoInformation about the the notification. May be nil.

DiscussionThis method is the preferred method for posting notifications.

NSNotificationCenter Class ReferenceInstance Methods

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

12

Page 13: NSNotificationCenter Class

AvailabilityAvailable in iOS 2.0 and later.

See Also– postNotificationName:object: (page 11)

Related Sample CodeEADemoSeismicXML

Declared inNSNotification.h

removeObserver:

Removes all the entries specifying a given observer from the receiver’s dispatch table.

- (void)removeObserver:(id)notificationObserver

ParametersnotificationObserver

The observer to remove. Must not be nil.

DiscussionBe sure to invoke this method (or removeObserver:name:object: (page 14)) before notificationObserveror 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 hadpreviously registered:

[[NSNotificationCenter defaultCenter] removeObserver:someObserver];

AvailabilityAvailable in iOS 2.0 and later.

See Also– removeObserver:name:object: (page 14)

Related Sample CodeAlternateViewsSimpleUndo

Declared inNSNotification.h

NSNotificationCenter Class ReferenceInstance Methods

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

13

Page 14: NSNotificationCenter Class

removeObserver:name:object:

Removes matching entries from the receiver’s dispatch table.

- (void)removeObserver:(id)notificationObserver name:(NSString *)notificationNameobject:(id)notificationSender

ParametersnotificationObserver

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.

notificationNameName of the notification to remove from dispatch table. Specify a notification name to remove onlyentries that specify this notification name. When nil, the receiver does not use notification names ascriteria for removal.

notificationSenderSender to remove from the dispatch table. Specify a notification sender to remove only entries that specifythis sender. When nil, the receiver does not use notification senders as criteria for removal.

DiscussionBe sure to invoke this method (or removeObserver: (page 13)) before the observer object or any object specifiedin addObserver:selector:name:object: (page 8) is deallocated.

AvailabilityAvailable in iOS 2.0 and later.

See Also– removeObserver: (page 13)

Related Sample CodeAddMusicAppPrefsAudio Mixer (MixerHost)EADemoKeyboardAccessory

Declared inNSNotification.h

NSNotificationCenter Class ReferenceInstance Methods

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

14

Page 15: NSNotificationCenter Class

This table describes the changes to NSNotificationCenter Class Reference .

NotesDate

Clarified discussion of addObserverForName:object:queue:usingBlock:.2010-08-03

Corrected description of memory management behavior and removingthe observer for addObserverForName:object:queue:usingBlock:.

2010-06-22

Modified the addObserverForName:object:usingBlock: description toextend return explanation and added release notes.

2010-04-29

Corrected method heading foraddObserverForName:object:queue:usingBlock:. Added trailing colon.

2009-09-01

Added addObserverForName:object:queue:usingBlock: method.2009-08-28

Updated for Mac OS X v10.6.2009-05-15

Removed a statement that the observer parameter can be nil in theremoveObserver:name:object: method.

2008-07-11

Updated for Mac OS X v10.52007-04-02

Clarified how a notification center manages observers in its dispatch table.2006-11-07

Updated return type of defaultCenter (page 7).

First publication of this content as a separate document.2006-05-23

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

15

Document Revision History

Page 16: NSNotificationCenter Class

Apple Inc.© 2010 Apple Inc.All rights reserved.

No part of this publication may be reproduced,stored in a retrieval system, or transmitted, in anyform or by any means, mechanical, electronic,photocopying, recording, or otherwise, withoutprior written permission of Apple Inc., with thefollowing exceptions: Any person is herebyauthorized to store documentation on a singlecomputer for personal use only and to printcopies of documentation for personal useprovided that the documentation containsApple’s copyright notice.

The Apple logo is a trademark of Apple Inc.

No licenses, express or implied, are granted withrespect to any of the technology described in thisdocument. Apple retains all intellectual propertyrights associated with the technology describedin this document. This document is intended toassist application developers to developapplications only for Apple-labeled computers.

Apple Inc.1 Infinite LoopCupertino, CA 95014408-996-1010

Apple, the Apple logo, Cocoa, Mac, Mac OS, andOS X are trademarks of Apple Inc., registered inthe United States and other countries.

IOS is a trademark or registered trademark ofCisco in the U.S. and other countries and is usedunder license.

Even though Apple has reviewed this document,APPLE MAKES NO WARRANTY OR REPRESENTATION,EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THISDOCUMENT, ITS QUALITY, ACCURACY,MERCHANTABILITY, OR FITNESS FOR A PARTICULARPURPOSE. AS A RESULT, THIS DOCUMENT IS PROVIDED“AS IS,” AND YOU, THE READER, ARE ASSUMING THEENTIRE RISK AS TO ITS QUALITY AND ACCURACY.

IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT,INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIALDAMAGES RESULTING FROM ANY DEFECT ORINACCURACY IN THIS DOCUMENT, even if advised ofthe possibility of such damages.

THE WARRANTY AND REMEDIES SET FORTH ABOVEARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORALOR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer,agent, or employee is authorized to make anymodification, extension, or addition to this warranty.

Some states do not allow the exclusion or limitationof implied warranties or liability for incidental orconsequential damages, so the above limitation orexclusion may not apply to you. This warranty givesyou specific legal rights, and you may also have otherrights which vary from state to state.


Recommended