Notification methods for iOS events

Source: Internet
Author: User
Tags naming convention notification center

1 manual broadcaster and listener (broadcaster and listeners)

2 Key-value Watch key value observing

3 Notification Hubs Notification Center

4 Contextual Notification Context notification

5 Weituo Delegate for observation

About the viewer
The Observer pattern is one of the most powerful ways to maintain an abstract relationship between two modules. The Observer pattern includes a module that publishes events that have occurred and instances of several other modules that respond to the event. It differs from the method of invoking the second module directly, because the first module does not need to focus on how many observers there are, thus achieving a more complete abstraction between the observer and the Observer.

Manual broadcaster and listener

Manual mode requires the broadcaster to maintain an array (Nsarray) or set (Nsset) of listeners. In the appropriate time to notify listeners of an event, the broadcaster directly invokes the relevant methods on each listener.

You may need a nsmutablearray, nsset, or nsmutabledictionary on the broadcaster class. Nsmutabledictionary is more appropriate for the type of event identifier as the key value for each listener. On the broadcaster you also need to have the listener registered and unregistered methods.
The method of giving messages to each object in Nsarray or Nsset is simple, as follows:

[Listenerscollection makeobjectsperformselector: @selector (Methodsupportedbyeverylistener)];
Pros: The broadcaster has complete control over the listener list.
Disadvantage: Manually adding or removing listeners in the collection (especially if they have not been maintained for other reasons). If you need to publish different messages, you need more manual work.

Key value Observation
The key value observation protocol is a great step towards automating the direction of the process. In many cases, broadcasters do not need to do anything.
Each cocoa object automatically processes the AddObserver:forKeyPath:options:context used to publish any object:. If the broadcaster's "setter" method follows certain rules, the "setter" method automatically triggers any listener's ObserveValueForKeyPath:ofObject:change:context: method.
For example, the following code adds an observer to the "source" object:

[source      addobserver:destination       forkeypath:@ "MyValue"      options:nskeyvaluechangenewkey       context:nil];
This sends a OBSERVEVALUEFORKEYPATH:OFOBJECT:CHANGE:CONTEXT: message to destination each time the Setmyvalue: method is called.
All you need to do is register the listener on the observed object and let the listener implement ObserveValueForKeyPath:ofObject:change:context:.

Advantages: Built-in and automatic. You can observe any key path. Support for dependency notifications.
Cons: Broadcasters cannot know who is listening. Method must conform to a naming convention to enable automatic observation of the operation of messages. Listeners must be removed before they are deleted, and the next notification will cause crashes and failures-but this is the same for all the methods indicated in the article.

Notification Center
The Nsnotificationcenter provides a more decoupled approach. The most typical application is any object pair that can send notifications to the center, while any object can listen to the notification of the center.
The code to send the notification is as follows:

[[nsnotificationcenter defaultcenter]       postnotificationname:@ "Mynotificationname"      object:broadcasterObject]; The code for the
register to receive notifications is as follows:

[[nsnotificationcenter defaultcenter]       Addobserver:listenerobject      selector: @selector (receivingmethodonlistener:)       name:@ "Mynotificationname"      object:nil];
You can specify a specific broadcaster object when registering for notifications, but this is not required. You may have noticed the defaultcenter . This is actually the only center you'll use in your app. Notifications are open to the entire application, so there is only one center. The
also has a nsdistributednotificationcenter. This is used for inter-application communication. There is only one center of that type on the entire computer.
Benefits:  the sender and recipient of the notification do not need to know each other. You can specify the specific method to receive notifications. The notification name can be any string. The
disadvantage:  requires more code than the key value observation. You must remove listeners before deleting them.

Context notification
if the observed property is a Nsmanagedojbect declaration attribute, you can listen   Nsmanagedobjectcontextobjectsdidchangenotification. This still uses the Nsnotification method   but is a bit different because Nsmanagedobject does not send notifications manually.
This method is registered as follows

[[nsnotificationcenter defaultcenter]       Addobserver:listenerobejct      selector: @selector (receivingmethodonlistener:)       name:NSManagedObjectContextObjectsDidChangeNotification       object:observedManagedObjectContext];
in Receivingmethodonlistener:, the userinfo of the notification is Nsinsertedobjectskey, Key values such as Nsupdatedobjectskey and Nsdeletedobjectskey give the affected collection of objects.

Pros: The simplest way to track changes throughout the Nsmanagedobjectcontext.
Cons: Only core data is not available to provide specific information beyond the impact object.

The delegate used for observation
The last cocoa simplified observer pattern is the delegate. Broadly speaking, delegates can not only deal with simple observations, but do not necessarily need to do more.
For example, all notifications for nsapplication and Nswindow are passed on to the delegate at the same time and processed by it. Some classes pass a message to their delegate-like notification without sending a notification at the same time. For example Nsmenu, send menuwillopen: delegate to it but not send the corresponding nsnotification.
To connect a delegate, simply call the following code on the object that supports the delegate:

[Object Setdelegate:delegateobject];
The object can receive any delegate messages it wants.

Pros: The classes that support it have detailed and specific information.
Disadvantage: The class must support delegates. There can be only one delegate connected to an object at a time.


Notification methods for iOS events

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.