5 methods of monitoring, observation, and notification in Cocoa

Source: Internet
Author: User
Tags notification center

CocoaListening, observing, andNotificationThe five methods are described in this article. This article introduces the observer mode in Objective C, which is also called the broadcaster/listener, publish/register, orNotification) And the value of each method. This article will include:

1. Manual broadcasters and listeners Broadcaster and listeners)

2. Key-Value observation Key Value Observing)

3. Notification center)

4. Context notification)

5. Delegate for observation)

About observer

The observer mode is one of the most powerful ways to maintain the abstract relationship between two modules. The observer mode includes a module that publishes an event and several instances of another module that responds to the event. It is different from calling the second module directly, because the first module does not need to focus on the number of observers, so as to achieve a more complete abstract relationship between the observer and the observer.

Manual broadcasters and listeners

Manually, the broadcaster needs to keep an array of NSArray listeners) or a collection of nssets ). When an event needs to be notified to the listener, the broadcaster directly calls related methods on each listener.

In the broadcaster class, you may need an NSMutableArray, NSSet, or NSMutableDictionary. NSMutableDictionary is more suitable for using the event identifier type as the key value for each listener. On the broadcaster, you also need to register the listener and cancel the registration.

The method for sending messages to each object in NSArray or NSSet is simple, as follows:

 
 
  1. [listenersCollection makeObjectsPerformSelector:@selector(methodSupportedByEveryListener)]; 

For more information, see Collections Programming Topics for Cocoa.

Advantage: the broadcaster has full control over the listener list.

Disadvantage: manually add or remove listeners in the collection, especially when the listener is not maintained for other reasons ). If you want to publish different messages, you need more manual work.

Key Value observation

The key value observation protocol has made great progress in automating the above process. In many cases, broadcasters do not need to do anything.

EachCocoaThe addObserver: forKeyPath: options: context: that is used to publish any object :. If the caster's "setter" method follows certain rules, the "setter" method will automatically trigger the observeValueForKeyPath: ofObject: change: context: Method of any listener.
For example, the following code adds an observer to the "source" object ::

 
 
  1. [source      addObserver:destination        
  2.    forKeyPath:@"myValue"     options:NSKeyValueChangeNewKey        
  3.     context:nil];       

In this way, an observeValueForKeyPath: ofObject: change: context: Message to destination will be sent every time setMyValue: method is called.

All you need to do is register the listener on the observed object and enable the listener to implement

 
 
  1. observeValueForKeyPath:ofObject:change:context: 

For more information, see NSKeyValueObserving Protocol Reference.

Advantage: built-in and automatic. You can observe any key path. Supports dependency notifications.

Disadvantage: the broadcaster cannot know who is listening. The method must comply with naming rules to automatically observe the message operation. The listener must be removed before being deleted. Otherwise, the subsequent notification will cause crash and failure-but this is the same for all methods mentioned in this article.

Notification center

Nsicationicationcenter provides a more decoupled approach. The most typical application is that any object can send notifications to the center, and any object can listen to notifications from the center.

The code for sending a notification is as follows:

 
 
  1. [[NSNotificationCenter defaultCenter]        
  2. postNotificationName:@"myNotificationName"     object:broadcasterObject];         

The code for registering to receive notifications is as follows:

 
 
  1.    
  2. [[NSNotificationCenter defaultCenter]      addObserver:listenerObject       
  3.  selector:@selector(receivingMethodOnListener:)      name:@"myNotificationName"     object:nil];   

You can specify a specific broadcaster object when registering a notification, but this is not required. You may have noticed defacenter center. In fact, this is the only center you will use in the application. The notification is open to the entire application, so there is only one center.

There is also an NSDistributedNotificationCenter. This is used for inter-Application Communication. There is only one center of this type on the entire computer.

For more information, see Notification Programming Topics for Cocoa.

Advantages:NotificationThe sender and receiver do not need to know the other party. You can specify the method for receiving notifications. The notification name can be any string.

Disadvantage: More code is required than the key value observation. The listener must be removed before deletion.

Context notification

If the observed attribute is a declared attribute of NSManagedOjbect, you can listen

 
 
  1. NSManagedObjectContextObjectsDidChangeNotification 

The NSNotification method is still used, but it is a little different because NSManagedObject does not send notifications manually.

The registration of this method is as follows:

 
 
  1. [[NSNotificationCenter defaultCenter]        
  2. addObserver:listenerObejct      selector:@selector(receivingMethodOnListener:)        
  3. name:NSManagedObjectContextObjectsDidChangeNotification   
  4.          object:observedManagedObjectContext];       

In receivingMethodOnListener:, key values such as NSInsertedObjectsKey, NSUpdatedObjectsKey, and NSDeletedObjectsKey in the userinfo of the notification give a set of affected objects.

For more information, see NSManagedObjectContext Class Reference

Advantage: it is the easiest way to track changes in the entire NSManagedObjectContext.

Disadvantage: it is only applicable to Core Data and does not provide specific information that affects objects. Delegate for observation

The last Cocoa simplified observer mode is delegation. In a broad sense, delegation can not only handle simple observations, but not necessarily require more. For example, all notifications of NSApplication and NSWindow are sent to the delegate at the same time for processing. Some Classes send messages similar to notifications to their delegates, instead of sending notifications at the same time. For example, NSMenu sends menuWillOpen: it delegates but does not send the corresponding NSNotification. To connect a delegate, you only need to call the following code on the object that supports the delegate:

 
 
  1. [object setDelegate:delegateObject];       

The object can receive any delegate message it wants.

For more information, see Cocoa Fundamentals Guide: Delegates and Data Sources.

Advantage: The classes supporting it have detailed and specific information.

Disadvantage: this class must supportDelegate. Only oneDelegateConnect to an object.

Summary: DetailsCocoaListening, observing, andNotificationThe content of the five methods has been introduced, and I hope this article will help you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.