How to choose Delegate, notifications, KVO (and the difference between them) in iOS

Source: Internet
Author: User
Tags notification center

Reprinted from: http://blog.csdn.net/dqjyong/article/details/7685933

When developing iOS apps, we often encounter a common problem: controllers[b] How to communicate without being overly coupled. There are three modes in the iOS app that are constantly appearing to achieve this communication:
1 Commissioned delegation
2 Notification hubs Notification Center
3 Key value observation key 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 controllers to exist in its own way and not to be coupled with other controllers on controllers. Controllers can create other controllers and they can communicate freely between them, but we do not want the controller to return to creating its own controller. 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 an iOS app as well as needing 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.

Three Advantages and disadvantages:

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

8. Often used to communicate between objects that have a parent-child relationship, such as the view of the controller and controller (self-added understanding)

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.

4. Often used in one-to-one communication. (Do not know whether it is a disadvantage or merit, can only be regarded as a characteristic)(self-added understanding)

advantages of notification :

1. No need to write how much code, implementation is relatively simple

2. For a given notification, multiple objects can react, that is, a one-to-many way 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. Third-party objects are 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 (compared to delegate).

advantages of KVO :

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

6. Can be a pair of more.

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.

1. Efficiency is certainly delegate higher than Nsnotification.

The delegate method is more direct than notification, and the most typical feature is that the delegate method often needs to focus on the return value, which is the result of the delegate method. For example,-windowshouldclose: You need to be concerned with whether the return is yes or No. So the delegate method often contains should, a very expressive word. Just like you do my delegate, I'll ask you I want to close the window would you like to? You need to give me an answer and I will decide what to do next, based on your answer. On the contrary, notification's biggest feature is not caring about the recipient's attitude, I just put out the notice, you accept not accept is your thing, and I do not care about the results. So notification often use did this word, such as nswindowdidresizenotification, then Nswindow object release this notification after nothing will not wait for the response of the recipient.

2. The difference between KVO and nsnotification:

Like delegate, the role of KVO and Nsnotification is also a class-to-class communication, unlike the Delegate 1) both are responsible for giving notice, the rest of the matter, so there is no return value; 2) delegate is just one-to-one, And these two can be a couple more. The two also have their own characteristics.

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
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. Userlnfo 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.

How to choose Delegate, notifications, KVO (and the difference between them) in iOS

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.