你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS 通知機制 Notifications (一)

iOS 通知機制 Notifications (一)

編輯:IOS開發綜合

Notifications


A 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


    A 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 +defaultCenter class 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: and enqueueNotification: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, and NSPostNow. 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 NSPostNow rather 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 NSNotificationCenter since 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 NSNotificationCoalescingOnName andNSNotificationCoalescingOnSender 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];

      [這邊暫時不翻譯了]
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved