1. Trang chủ >
  2. Công Nghệ Thông Tin >
  3. Kỹ thuật lập trình >

29€ Sending Notifications with NSNotificationCenter

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.67 MB, 89 trang )


ficationCenter class. We retrieve the default notification center object using the

defaultCenter class method of NSNotificationCenter.



Notifications are objects of type NSNotification. A notification object has a name

(specified as NSString) and can carry two key pieces of information:

You can specify the name of your notifications yourself. You don't have

to use an API for that. Just make sure that your notification names are

unique enough that they won't clash with a system notification.



Sender Object

This is the instance of the object that fires the notification. The observer can access

this object using the object instance methof of the NSNotification class.

User-Info Dictionary

This is an optional dictionary that the sender object can create and send alongside

a notification object. This dictionary usually contains more information about the

notification. For instance, when a keyboard is about to get displayed in iOS for any

component inside your app, iOS sends the UIKeyboardWillShowNotification notification to the default notification center. The user-info dictionary of this notification contains values such as the rectangle of the keyboard before and after animation and the animation duration of the keyboard. Using this data, an observer

can make a decision as to, for instance, what to do with UI components that potentially will be obstructed once the keyboard gets displayed on the screen.

Notifications are a great way of implementing decoupled code. By that

I mean, using notifications, you can get rid of completion handlers and

delegation. However, there is one potential caveat about notifications:

they are not delivered immediately. They are dispatched by notification

centers, and the implementation of NSNotificationCenter is hidden

from application programmers. Delivery might sometimes be delayed

by a few milliseconds or in extreme cases (which I have never encountered) a few seconds. As a result, it is up to you to decide where to and

where not to use notifications.



In order to construct a notification of type NSNotification, use the notificationWith

Name:object:userInfo: class method of NSNotification like so:

It is best to suffix your notification names with the word Notification.

For instance, it is permitted to give your notification a name similar to

ResultOfAppendingTwoStrings. However, it is better to give the name

ResultOfAppendingTwoStringsNotification, as that clearly says what

this name belongs to.



1.29 Sending Notifications with NSNotificationCenter | 101



Let's have a look at an example. We'll simply take a first name and a last name, append

them to create one string (first name + last name) and then broadcast the result using

the default notification center. We will do that in the implementation of our app delegate as soon as the user launches our app:

#import "AppDelegate.h"

@implementation AppDelegate

@synthesize window = _window;

/* The notification name */

const NSString *ResultOfAppendingTwoStringsNotification =

@"ResultOfAppendingTwoStringsNotification";

/* Keys inside the dictionary that our notification sends */

const NSString

*ResultOfAppendingTwoStringsFirstStringInfoKey = @"firstString";

const NSString

*ResultOfAppendingTwoStringsSecondStringInfoKey = @"secondString";

const NSString

*ResultOfAppendingTwoStringsResultStringInfoKey = @"resultString";

- (BOOL)

application:(UIApplication *)application

didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

NSString *firstName = @"Anthony";

NSString *lastName = @"Robbins";

NSString *fullName = [firstName stringByAppendingString:lastName];

NSArray *objects = [[NSArray alloc] initWithObjects:

firstName,

lastName,

fullName,

nil];

NSArray *keys = [[NSArray alloc] initWithObjects:

ResultOfAppendingTwoStringsFirstStringInfoKey,

ResultOfAppendingTwoStringsSecondStringInfoKey,

ResultOfAppendingTwoStringsResultStringInfoKey,

nil];

NSDictionary *userInfo = [[NSDictionary alloc] initWithObjects:objects

forKeys:keys];

NSNotification *notificationObject =

[NSNotification

notificationWithName:(NSString *)ResultOfAppendingTwoStringsNotification

object:self

userInfo:userInfo];

[[NSNotificationCenter defaultCenter] postNotification:notificationObject];



102 | Chapter 1: The Basics



}



self.window = [[UIWindow alloc] initWithFrame:

[[UIScreen mainScreen] bounds]];

self.window.backgroundColor = [UIColor whiteColor];

[self.window makeKeyAndVisible];

return YES;



Of course, you don't have to specify an object or a user-info dictionary for every notification that you wish to broadcast. However, if you are working with a team of developers on the same app or if you are writing a static library, I suggest that you fully

document your notifications and clearly mention whether your notifications carry an

object and/or an user-info dictionary with them. If they do, you must say what object

each notification carries and what keys and values are inside the user-info dictionary.

If you are planning on not sending an object or a user-info dictionary, then I suggest

you use the postNotificationName:object: instance method of NSBundle. Specify a

string that represents the name of your notification as the first parameter, and nil as

the second paramater, which is the object that should be carried with the notification.

Here is an example:

#import "AppDelegate.h"

@implementation AppDelegate

@synthesize window = _window;

/* The notification name */

const NSString *NetworkConnectivityWasFoundNotification =

@"NetworkConnectivityWasFoundNotification";

- (BOOL)

application:(UIApplication *)application

didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

[[NSNotificationCenter defaultCenter]

postNotificationName:(NSString *)NetworkConnectivityWasFoundNotification

object:nil];



}



self.window = [[UIWindow alloc] initWithFrame:

[[UIScreen mainScreen] bounds]];

self.window.backgroundColor = [UIColor whiteColor];

[self.window makeKeyAndVisible];

return YES;



See Also

XXX



1.29 Sending Notifications with NSNotificationCenter | 103



1.30 Listening for Notifications Sent From

NSNotificationCenter

Problem

You want to listen for different system and custom notifications broadcast using NSNo

tificationCenter.



Solution

Add your observer object to the notification center using the addObserver:selec

tor:name:object: instance method of NSNotificationCenter before a notification is

broadcast. To stop observing a notification, use the removeObserver:name:object: instance method of NSNotificationCenter and pass your observer object, then the name

of the notification that you want to stop observing and the object that you originally

subscribed to (this will be explained in detail in the Discussion section of this recipe).



Discussion

Any object can broadcast a notification and any object within the same app can opt

into listening for notifications with specific names. Two notifications with the same

name can be broadcast, but they must come from two different objects. For instance,

you can have a notification with the name of DOWNLOAD_COMPLETED that gets fired from

two classes, one being a download manager that downloads images from the internet

and another being a download manager that downloads data from an accessory connected to the iOS device. An observer might be interested only in the notifications of

this name coming from a specific object, for instance, the download manager that

downloads data from the accessory. You can specify this source object (broadcaster)

when you start listening for notifications, using the object parameter of the addOb

server:selector:name:object: method of the notification center.

Here is a brief description of each of the parameters that the addObserver:selec

tor:name:object: accepts:

addObserver



The object that will receive the notifications (observer).

selector



The selector (method) to be called on the observer when the notification is broadcasted and received by the observer. This method takes a single argument of type

NSNotification.

name



The name of the notification to observe.



104 | Chapter 1: The Basics



object



Optionally specifies the source of the broadcast notification. If this parameter is

nil, notifications of the specified name will be received by the observer regardless

of which object broadcasts them. If this parameter is set, only the notifications of

the specified name that are broadcast by the given object will be observed.

In Recipe 1.29 we learned how to post notifications. Let's now try observing the notification that we learned to post there.

#import "AppDelegate.h"

@implementation AppDelegate

@synthesize window = _window;

/* The notification name */

const NSString *ResultOfAppendingTwoStringsNotification =

@"ResultOfAppendingTwoStringsNotification";

/* Keys inside the dictionary that our notification sends */

const NSString

*ResultOfAppendingTwoStringsFirstStringInfoKey = @"firstString";

const NSString

*ResultOfAppendingTwoStringsSecondStringInfoKey = @"secondString";

const NSString

*ResultOfAppendingTwoStringsResultStringInfoKey = @"resultString";

- (void) broadcastNotification{

NSString *firstName = @"Anthony";

NSString *lastName = @"Robbins";

NSString *fullName = [firstName stringByAppendingString:lastName];

NSArray *objects = [[NSArray alloc] initWithObjects:

firstName,

lastName,

fullName,

nil];

NSArray *keys = [[NSArray alloc] initWithObjects:

ResultOfAppendingTwoStringsFirstStringInfoKey,

ResultOfAppendingTwoStringsSecondStringInfoKey,

ResultOfAppendingTwoStringsResultStringInfoKey,

nil];

NSDictionary *userInfo = [[NSDictionary alloc] initWithObjects:objects

forKeys:keys];

NSNotification *notificationObject =

[NSNotification

notificationWithName:(NSString *)ResultOfAppendingTwoStringsNotification

object:self



1.30 Listening for Notifications Sent From NSNotificationCenter | 105



Xem Thêm
Tải bản đầy đủ (.pdf) (89 trang)

×