iOS 通知机制 Notifications (一)

来源:互联网 发布:mysql 最近一条记录 编辑:程序博客网 时间:2024/04/26 20:12

notification encapsulates information about an event, such as a window gaining focus or a network connection closing. Objects that need to know about an event (for example, a file that needs to know when its window is about to be closed) register with the notification center that it wants to be notified when that event happens. When the event does happen, a notification is posted to the notification center, which immediately broadcasts the notification to all registered objects. Optionally, a notification is queued in a notification queue, which posts notifications to a notification center after it delays specified notifications and coalesces notifications that are similar according to some specified criteria you specify.

通知封装了一个事件的信息,比如窗口获取了焦点或者网络连接关闭事件。需要知道一个事件的对象(例如,一个文件时,需要知道它的窗口即将关闭)注册通知中心,当这个事件发生时对象得到通知。当这个事件确实发生了,通知中心发出通知,立刻广播通知到所有注册的对象。或者,通知被放到通知队列中,这个通知延迟指定的通知并且根据指定的标准聚合类似的通知,然后会发布通知到通知中心。


Notifications and Their Rationale

The standard way to pass information between objects ismessage passing—one object invokes the method of another object. However, message passing requires that the object sending the message know who the receiver is and what messages it responds to. At times, this tight coupling of two objects is undesirable—most notably because it would join together two otherwise independent subsystems. For these cases, a broadcast model is introduced: An object posts a notification, which is dispatched to the appropriate observers through anNSNotificationCenter object, or simply notification center.

An NSNotification object (referred to as a notification) contains a name, an object, and an optional dictionary. 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 that posted the notification itself. The dictionary may contain additional information about the event.

通知以及其原理

对象间传递信息的标准方法是 消息传递——一个对象调用另一个对象中方法。但是消息传递机制中,发送消息的对象需要知道接收消息的对象以及接收对象要相应什么方法。有时,这种两个对象的紧密耦合是不可取的——尤其是两个原本独立的子系统因此联系起来。由于这些情况,引入了广播模型:一个对象发布通知,通知通过NSNotification对象被派到相应的观察者去,或者只是送到通知中心。一个NSNotification对象(称为通知)包含一个名字,一个对象,和一个可选的字典。名字是识别通知的标记。对象是任何发布通知的对象,典型的,就是发布通知本身的对象。字典包含了事件的额外信息。

Notification names: Notification names are typically defined as constant string variables—for example,NSWindowDidBecomeMainNotification. Usually the value of the string is similar to the variable name. You should not, however, use the string value in your code, you should always use the name of the variable—see“Registering for Local Notifications” for an example.

Many Cocoa frameworks make extensive use of notifications to allow objects to react to events they are interested in. The notifications sent by each class are described in the class’s reference documentation, under the “Notifications” section.

通知名字: 通知名字一般是字符串常量,例如NSWindowDidBecomeMainNotification。

许多cocoa 框架使用了大量的通知让对象响应它们感兴趣的事件。 每个类发送的对象卸载类的参考文档里,在 “Notifications” 区域下面。

Any object may post a notification. Other objects can register themselves with the notification center as observers to receive notifications when they are posted. The notification center takes care of broadcasting notifications to the registered observers, if any. The object posting the notification, the object included in the notification, and the observer of the notification may all be different objects or the same object. Objects that post notifications need not know anything about the observers. On the other hand, observers need to know at least the notification name and keys to the dictionary if provided.

任何对象都可能发出通知。其他对象可以注册到通知作为观察者去接收发过来的通知。通知中心广播通知到注册的观察者。发布通知的对象不需要知道观察者。另外观察者只是需要知道通知名称和提供的字典(如果有的话)。

Notification and Delegation

Using the notification system is similar to using delegation but has these differences:

  • Any number of objects may receive the notification, not just the delegate object. This precludes returning a value.
  • An object may receive any message you like from the notification center, not just the predefined delegate methods.
  • The object posting the notification does not even have to know the observer exists.
通知和代理使用通知系统和使用代理有点类似,但是有以下不同点:

1,任何对象都可能接收通知,不仅仅代理对象。这样不需要返回值。

2,任何对象都可以从通知中心接收你想要的消息,不仅仅预先定义的代理方法。

3,发布通知的对象甚至都不需要知道观察者的存在。


Notification Centers


notification center manages the sending and receiving of notifications. It notifies all observers of notifications meeting specific criteria. The notification information is encapsulated inNSNotification objects. Client objects register themselves with the notification center as observers of specific notifications posted by other objects. When an event occurs, an object posts an appropriate notification to the notification center. (See “Posting a Notification” for more on posting notifications.) The notification center dispatches amessage to each registered observer, passing the notification as the sole argument. It is possible for the posting object and the observing object to be the same.

Cocoa includes two types of notification centers:

  • The NSNotificationCenter class manages notifications within a single process.
  • The NSDistributedNotificationCenter class manages notifications across multiple processes on a single computer.
通知中心

通知中心管理着发送和接收通知。它通知所有满足指定准则的观察者。 通知信息封装在NSNotification对象中。客户对象注册到通知中心中。

Cocoa 包括两种类型的通知中心

1,NSNotificationCenter:管理单一进程内的通知。

2,NSDistributedNotificationCenter :管理一台电脑上的多线程通知。

NSNotificationCenter

Each process has a default notification center that you access with theNSNotificationCenter +defaultCenterclass method. This notification center handles notifications within a single process. For communication between processes on the same machine, use a distributed notification center (see“NSDistributedNotificationCenter”).

A notification center delivers notifications to observers synchronously. In other words, when posting a notification, control does not return to the poster until all observers have received and processed the notification. To send notifications asynchronously use a notification queue, which is described in“Notification Queues.”

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.

通知中心同步地传递通知给观察者。换句话说,当发布一个通知时,直到所有的观察者都收到以及处理通知后,发布者才能重新控制发布。要异步地发送通知,要使用通知队列。请参考通知队列。

在多线程的应用中,通知总是在它被发出的线程中传递,这可能与观察者注册的线程不一样。

NSDistributedNotificationCenter


Each process has a default distributed notification center that you access with theNSDistributedNotificationCenter +defaultCenter class method. This distributed notification center handles notifications that can be sent between processes on a single machine. For communication between processes on different machines, use distributed objects (see Distributed Objects Programming Topics).

Posting a distributed notification is an expensive operation. The notification gets sent to a systemwide server that then distributes it to all the processes that have objects registered for distributed notifications. The latency between posting the notification and the notification’s arrival in another process is unbounded. In fact, if too many notifications are being posted and the server’s queue fills up, notifications can be dropped.

Distributed notifications are delivered via a process’s run loop. A process must be running a run loop in one of the “common” modes, such asNSDefaultRunLoopMode, to receive a distributed notification. If the receiving process is multithreaded, do not depend on the notification arriving on the main thread. The notification is usually delivered to the main thread’s run loop, but other threads could also receive the notification.

Whereas a regular notification center allows any object to be observed, a distributed notification center is restricted to observing a string object. Because the posting object and the observer may be in different processes, notifications cannot contain pointers to arbitrary objects. Therefore, a distributed notification center requires notifications to use a string as the notification object. Notification matching is done based on this string, rather than an object pointer.

[暂时不翻译这段]

Notification Queues


NSNotificationQueue objects, or simply,notification queues, act as buffers for notification centers (instances ofNSNotificationCenter). The NSNotificationQueue class contributes two important features to the Foundation Kit’s notification mechanism: the coalescing of notifications and asynchronous posting.


通知队列

通知对象对象,充当通知中心的缓冲区。(NSNotificationCenter的实例)。NSNotificationQueue类为Foundation Kit通知机制贡献了两个重要的特性:聚合通知以及异步发布。

Notification Queue Basics


Using the NSNotificationCenter’s postNotification: method and its variants, you can post a notification to a notification center. However, the invocation of the method is synchronous: before the posting object can resume its thread of execution, it must wait until the notification center dispatches the notification to all observers and returns. A notification queue, on the other hand, maintains notifications (instances ofNSNotification) generally in a First In First Out (FIFO) order. When a notification rises to the front of the queue, the queue posts it to the notification center, which in turn dispatches the notification to all objects registered as observers.

Every thread has a default notification queue, which is associated with the default notification center for the process. You cancreate your own notification queues and have multiple queues per center and thread. 

通知队列基础

使用 NSNotificationCenter的postNotification:方法以及它的变量,你可以发布一个通知到通知中心。然而,这个方法的调用是同步的:发布对象必须等待通知中心派遣通知给所有观察者并且返回后才能恢复执行线程。而 通知队列,大体上以先进先出的顺序保留着通知 (NSNotification的实例)

每一个线程都有一个默认的通知队列,它与进程的默认的通知中心有关。你可以创建自己的通知队列。并且每个中心和线程都可以有多个通知队列。

Posting Notifications Asynchronously


With NSNotificationQueue’s enqueueNotification:postingStyle: andenqueueNotification:postingStyle:coalesceMask:forModes: methods, you can post a notification asynchronously to the current thread by putting it in a queue. These methods immediately return to the invoking object after putting the notification in the queue.

Note: When the thread where a notification is enqueued terminates before the notification queue posts the notification to its notification center, the notification is not posted. See“Delivering Notifications To Particular Threads” to learn how to post a notification to a different thread.


The notification queue is emptied and its notifications posted based on the posting style and run loop mode specified in the enqueuing method. The mode argument specifies the run loop mode in which the queue will be emptied. For example, if you specify NSModalPanelRunLoopMode, the notifications will be posted only when the run loop is in this mode. If the run loop is not currently in this mode, the notifications wait until the next time that mode is entered. See“Run Loop Modes” in Threading Programming Guide for more information.

Posting to a notification queue can occur in one of three different styles:NSPostASAP, NSPostWhenIdle, andNSPostNow. These styles are described in the following sections.

异步发送通知。

注意:在通知队列发布通知到通知中心之前,通知所造的线程终止了,通知将不会被发送。See “Delivering Notifications To Particular Threads” to learn how to post a notification to a different thread.

这段我看不懂

Posting As Soon As Possible


Any notification queued with the NSPostASAP style is posted to the notification center when the current iteration of the run loop completes, assuming the current run loop mode matches the requested mode. (If the requested and current modes are different, the notification is posted when the requested mode is entered.) Because the run loop can make multiple callouts during each iteration, the notification may or may not get delivered as soon as the current callout exits and control returns to the run loop. Other callouts may take place first, such as a timer or source firing or other asynchronous notifications being delivered.

You typically use the NSPostASAP posting style for an expensive resource, such as the display server. When many clients draw on the window buffer during a callout from the run loop, it is expensive to flush the buffer to the display server after every draw operation. In this situation, each draw... method enqueues some notification such as “FlushTheServer” with coalescing on name and object specified and with a posting style ofNSPostASAP. As a result, only one of those notifications is dispatched at the end of the run loop and the window buffer is flushed only once.

Posting When Idle


A notification queued with the NSPostWhenIdle style is posted only when the run loop is in a wait state. In this state, there’s nothing in the run loop’s input channels, be it timers or other asynchronous events. A typical example of queuing with theNSPostWhenIdle style occurs when the user types text, and the program displays the size of the text in bytes somewhere. It would be very expensive (and not very useful) to update the text field size after each character the user types, especially if the user types quickly. In this case, the program queues a notification, such as “ChangeTheDisplayedSize,” with coalescing turned on and a posting style ofNSPostWhenIdle after each character typed. When the user stops typing, the single “ChangeTheDisplayedSize” notification in the queue (due to coalescing) is posted when the run loop enters its wait state and the display is updated. Note that a run loop that is about to exit (which occurs when all of the input channels have expired) is not in a wait state and thus will not post a notification.

Posting Immediately


A notification queued with NSPostNow is posted immediately after coalescing to the notification center. You queue a notification withNSPostNow (or post one with postNotification:) when you do not require asynchronous calling behavior. For many programming situations, synchronous behavior is not only allowable but desirable: You want the notification center to return after dispatching so you can be sure that observing objects have received and processed the notification. Of course, you should useenqueueNotification... with NSPostNowrather than use postNotification: when there are similar notifications in the queue that you want to remove through coalescing.

Coalescing Notifications


In some situations, you may want to post a notification if a given event occurs at least once, but you want to post no more than one notification even if the event occurs multiple times. For example, in an application that receives data in discrete packets, upon receipt of a packet you may wish to post a notification to signify that the data needs to be processed. If multiple packets arrive within a given time period, however, you do not want to post multiple notifications. Moreover, the object that posts these notifications may not have any way of knowing whether more packets are coming or not, whether the posting method is called in a loop or not.

In some situations it may be possible to simply set a Boolean flag (whether an instance variable of an object or a global variable) to denote that an event has occurred and to suppress posting of further notifications until the flag is cleared. If this is not possible, however, in this situation you cannot directly use NSNotificationCentersince its behavior is synchronous—notifications are posted before returning, thus there is no opportunity for "ignoring” duplicate notifications; moreover, anNSNotificationCenter instance has no way of knowing whether more notifications are coming or not.

Rather than posting a notification to a notification center, therefore, you can add the notification to anNSNotificationQueue instance specifying an appropriate option forcoalescing. Coalescing is a process that removes from a queue notifications that are similar in some way to a notification that was queued earlier. You indicate the criteria for similarity by specifying one or more of the following constants in the third argument of the enqueueNotification:postingStyle:coalesceMask:forModes: method.

NSNotificationNoCoalescing

Do not coalesce notifications in the queue.

NSNotificationCoalescingOnName

Coalesce notifications with the same name.

NSNotificationCoalescingOnSender

Coalesce notifications with the same object.

You can perform a bitwise-OR operation with the NSNotificationCoalescingOnNameandNSNotificationCoalescingOnSender constants to specify coalescing using both the notification name and notification object. The following example illustrates how you might use a queue to ensure that, within a given event loop cycle, all notifications named MyNotificationName are coalesced into a single notification.

// MyNotificationName defined globally


NSString *MyNotificationName = @"MyNotification";


 


id object = <#The object associated with the notification#>;


NSNotification *myNotification =


        [NSNotification notificationWithName:MyNotificationName object:object]


[[NSNotificationQueue defaultQueue]


        enqueueNotification:myNotification


        postingStyle:NSPostWhenIdle


        coalesceMask:NSNotificationCoalescingOnName


        forModes:nil];

[这边暂时不翻译了]
0 0
原创粉丝点击