iOS development: Selection of delegate, notification, KVO

Source: Internet
Author: User
Tags definition requires notification center

The functions of delegate, notification and KVO are similar, so how do you choose these methods in actual programming?

When developing iOS apps, we often encounter a common problem: how to communicate between controllers without too much coupling. There are three different modes of application in iOS to achieve this kind of communication:

1. Entrust delegation;

2. Notification Centre Notification Center;

3. Key value observation key value OBSERVING,KVO

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

The following are all based on my development experience to discuss these three patterns. I'm going to talk about why I think that a pattern is better than another and why I think it's better to have a pattern in a certain environment. The reasons I gave are not the Bible, but the personal point of view. If you have a different point of view or can be added to the place, you can contact me to discuss.

What are the top three models?

Three modes are one object passing events to another, and do not have to be coupled. The three patterns are objects that inform the method of an event, or, more precisely, a way to allow other objects to receive such an event. This is a very common and necessary task for an object, because without communication, the controllers will not be integrated into the entire application. Another purpose of the controller is to be as self-contained as possible. We want controllers to exist in our 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 do not want controller to return to creating their own controller. If we are coupled with them, then we will not be able to reuse them and completely lose control of an independent component in the application.

These three modes provide a means of communicating with controllers (which can be other objects). The following describes how to use these patterns in iOS applications, 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 that we were constantly using "delegate" and throughout the SDK. Delegation mode is not an iOS-specific model, but rather relies on the programming background you have in the past. This pattern may not be obvious for its advantages and why it is used frequently.

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

Advantages of Delegate:

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

2. If a method in delegate is not implemented, a compile warning/error occurs

3. Protocol must be defined within scope of controller

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

5. You can define multiple different protocols in a single controller, each with a different delegates

6. No third party object requires the maintenance/monitoring of the communication process.

7. The return value of the protocol method that can receive calls. This means that delegate can provide feedback to 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 agent object, you need to carefully change the delegate to nil. Once the setting fails, the call to dispose of the object will appear with memory crash

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

Notification

There is a concept of "Notification Center" in iOS application development. It is a single instance object that allows some objects to be notified when an event occurs. It allows us to meet the Controller's communication with an arbitrary object in a low degree of coupling. The basic feature of this pattern is to allow other objects to receive messages generated by an event occurring in the controller, controller with a key (notification name). This is anonymous for 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, to achieve relatively simple;

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

3.controller can pass the context object (dictionary), the context object carries the custom information about sending the notification

Disadvantages:

1. In the compilation period will not check whether the notice can be observed by the correct treatment;

2. In releasing the registered object, it is necessary to cancel the registration at the Notification Centre;

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

4. A third party is required to manage the relationship between the controller and the Observer object to the favorite one;

5.controller and the observer need to know in advance the name of the notice, UserInfo dictionary keys. If these are not defined in the work interval, then there will be an unsynchronized situation;

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

KVO

KVO is an object that can observe the value of another object's properties and can discover the value change. 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 be controller, but not controller). This is a way for an object to be synchronized with another object, i.e., when the state of another object changes, the object responds immediately. It can only be used to respond to attributes and not to respond to methods or actions.

Advantages:

1. The ability to provide a simple way to achieve synchronization between two objects. For example: Model and view synchronization between;

2. Ability to respond to changes in the state of objects that are not created by us, i.e. internal objects, without changing the implementation of internal objects (SKD objects);

3. The latest value and previous value of the property to be able to provide observation;

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

5. Complete the abstraction of the object of observation 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 does not appear with warnings and checks;

2. Property refactoring will cause our observation code to be no longer available;

3. The complex "IF" statement requires that the object is observing multiple values. This is because all the observation code is pointed through a method;

4. There is no 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, every kind of thing is the case, the question is how to choose the right thing in the right time in the correct environment. Let's talk about how to play their respective advantages, in which case, which mode to use. Note that there is no right or wrong to use any of the patterns, only more appropriate or unsuitable. Each pattern provides an object with a way 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 has clear practicality for a particular requirement. The other two models have similar uses and are often used to communicate between controller. So where do we use one of these?

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

I think the use of naming rules for protocols and protocol method definitions is easy for a clear understanding of the communication between controllers. The effort to define these protocols will enhance the readability of your code and better track your app. Agent protocol changes and implementation can be checked by the compiler, if not will be in the development process will appear at least crash, and not just let some things work abnormally. Even in the same event notification multiple controllers scenario, as long as your application at the controller level has a good structure, messages will be delivered at that level. This level can be passed backwards until all the controllers that need to know the event are known.

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

Based on experience, if it is the time of the attribute layer, whether it is in the object that does not need programming or is tightly bound to the model object of a View object, I only use observation. For other events, I will use the delegate mode. If for some reason I cannot use delegate, I will first estimate if there is a serious error in my app architecture. If there are no errors, then use notification.

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.