What are the differences and connections between Nsnotification, delegate, and Kvo in iOS?

Source: Internet
Author: User
Tags notification center

In front of the delegate, notification and KVO, and the actual use of the steps, we can not help but have a question, their function is similar, then in the actual programming, how to choose these methods?

On the internet to see a blog detailed analysis of the differences between the three and their respective advantages, the blog address is http://blog.shinetech.com/2011/06/14/ delegation-notification-and-observation/, because the blog is written in English, the following translation into Chinese.

When developing iOS apps, we often encounter a common problem: how to communicate between controllers without being overly coupled. There are three modes in the iOS app that are constantly appearing to achieve this communication:

1. Entrust delegation;

2. Notification Centre Notification Center;

3. Key value Observing,kvo

So why do we need these patterns and when to use it and when not to do it.

The following is a complete discussion of the three models based on my development experience. I'll discuss why I feel that some pattern is better than the other and why I feel that a certain pattern is better in a certain environment. The reason I give is not the Bible, but just my personal opinion. If you have a different point of view or you can add a place, you can contact me and discuss it together.

What are the three modes above?

Three modes are one object passing events to another object, and do not have them coupled. Three modes are objects that inform the way an event has occurred, or, more accurately, the method that allows other objects to receive such an event. This is a very common and must-do task for an object, because without communication, controllers will not be integrated into the entire application. Another purpose of the controller is to self-contain as much as possible. We want the controllers to exist in its own way and not to be coupled with other controllers at the controllers level. Controllers can wear other controllers and they can communicate freely, but we don't want the controller to return to the controller that created it. If we are coupling them, then we will not be able to reuse them and completely lose control of a separate component in the application.

These three modes give controllers (or other objects) a way to communicate. The following describes how to use these patterns in iOS apps, as well as the need to be aware that they are used elsewhere, and that they do exist.

    • Delegation

When we first wrote iOS apps, we noticed the constant use of "delegate" and throughout the SDK. Delegation mode is not an iOS-specific pattern, but relies on the programming background you have in the past. For its advantages and why it is often used, this pattern may not be obvious.

The basic feature of delegation is that a controller defines a protocol (a series of method definitions). This protocol describes what a delegate object must do in order to respond to a controller's events. The deal is Delegator said, "If you want to be my delegate, then you have to implement these methods." Implementing these methods is to allow the controller to invoke these methods in its delegate, and its delegate knows when to invoke which method. Delegate can be any type of object, so the controller is not coupled to an object, but when the object tries to tell the delegate something, the object can determine that the delegate will respond.

Advantages of Delegate:

1. Very strict grammar. All events that will be heard must be clearly defined in the delegate protocol.

2. If one of the methods in delegate is not implemented then a compile warning/error will appear

3. The protocol must be defined within the scope of the controller

4. The control flow in an application is traceable and recognizable;

5. In one controller you can define multiple different protocols, each with a different delegates

6. There is no third-party object required to maintain/monitor the communication process.

7. The return value of the protocol method that can receive the call. This means that delegate can provide feedback to the controller

Disadvantages:

1. Need to define a lot of code: 1. Protocol definition; 2.controller delegate property; 3. Implement delegate method definition in delegate itself

2. When releasing the proxy object, be careful to change the delegate to nil. Once the setting fails, the call to dispose of the object will show memory crash

3. There are multiple delegate objects in a controller, and delegate is in compliance with the same protocol, but it is still difficult to tell multiple objects the same event, but it is possible.

    • Notification

There is a concept of "Notification Center" in iOS app development. It is a singleton object that allows some objects to be notified when an event occurs. It allows us to meet the purpose of communication between the Controller and an arbitrary object in a low-level coupling condition. The basic feature of this pattern is that the controller uses a key (the notification name) to allow other objects to receive a message from an event that occurs in the controller. This is anonymous for the controller, and other objects that use the same key to register the notification (i.e., the observer) can respond to the notification event.

Advantage:

1. Do not need to write how much code, implementation is relatively simple;

2. For a given notification, multiple objects can react, that is, 1-to-many ways to achieve a simple

3.controller is able to pass a context object (dictionary), and the context object carries a custom message about sending notifications

Disadvantages:

1. In the compilation period will not check whether the notification can be properly handled by the observer;

2. When releasing the registered object, you need to cancel the registration in the Notification Center;

3. In the commissioning of the application of the work and control process difficult to track;

4. A third party is required to manage the connection between the Controller and the Observer object;

5.controller and observers need to know the notification name, UserInfo dictionary keys in advance. If these are not defined in the work interval, then there is an unsynchronized situation;

6. After the notification is issued, the controller cannot obtain any feedback from the observer.

    • KVO

KVO is the value of an object's ability to observe the properties of another object, and to discover the change in value. The previous two modes are more suitable for a controller to communicate with any other object, while KVO is more suitable for any type of object to listen for changes to another arbitrary object (this can also be a controller, but is generally not a controller). This is one way to keep an object synchronized with another object, that is, when the state of another object changes, the observer responds immediately. It can only be used to react to a property, not to respond to a method or action .

Advantages:

1. The ability to provide a simple way to achieve synchronization between two objects. Example: synchronization between model and view;

2. Be able to respond to changes in the state of objects not created by us, i.e. internal objects, without changing the implementation of the inner object (SKD object);

3. Ability to provide the latest value of the observed properties and previous values;

4. Use key paths to observe attributes, so you can also observe nested objects;

5. The abstraction of the observed object is completed because no additional code is required to allow the observed value to be observed

Disadvantages:

1. The attributes we observe must be defined using strings. Therefore, the compiler will not appear warning and check;

2. Refactoring the property will cause our observation code to be no longer available;

3. A complex "IF" statement requires that the object is observing multiple values. This is because all the observation code is directed by a method;

4. You do not need to remove the observer when releasing the Observer.

Summarize:

From the above analysis can be seen in the 3 design patterns have their own advantages and disadvantages. In fact, any kind of thing is so, the question is how to choose the right thing in the right environment at the correct time. Here's how to play their respective strengths and in which case to use which mode. Note that there is no right or wrong to use any one mode, only more suitable or unsuitable. Each mode provides a way for an object to notify an event to another object, and the former does not need to know the listener. In these three models, I think KVO has the clearest use case and is clearly useful for a particular requirement. The other two models have similar uses and are often used to communicate between controllers. So what are we going to do with one of these things?

Based on my experience developing iOS apps, I've found some excessive use of notification patterns. I personally do not like to use notification hubs. I find it difficult to use notification hubs to grasp the application execution process. UserInfo dictionaries's keys are passed around causing the loss of synchronization, and there is a need to define too many constants in the public space. For a developer working on an existing project, it is difficult to understand the process of the application if the notification hub is used too much.

I think it's easy to use a well-named protocol and protocol method definition for a clear understanding of the communication between controllers. Efforts to define these protocol methods will enhance the readability of your code and better track your app. Proxy protocol changes and implementations can be checked out by the compiler, and if not, there will be at least crash in the development process, rather than just getting things to work abnormally. Even in scenarios where the same event notifies a multi-controller, the message is passed at that level as long as your app has a good structure at the controller level. This level can be passed backwards until all controllers that need to know the event are known.

Of course there will be exceptions where the delegation pattern is not appropriate, and notification may be more effective. For example: All controllers in the app need to know an event. However, these types of scenes rarely appear. Another example is when you build a schema and need to notify the event to be applied in the running.

Based on experience, if it is the time of the attribute layer, whether it is a model object that does not require programming or tightly binds a view object, I only use observation. For other events, I will use the delegate mode. If for some reason I can't use delegate, I'll start by estimating if there's a serious error in my app architecture. If there are no errors, then use notification.

PS: Because the author's memory is not very good, many things to see after easy to forget. This article is the author in other places to see, feel good to write, copy sticky days come over. To facilitate the author in later leisure time reference.

What are the differences and connections between Nsnotification, delegate, and Kvo in iOS?

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.