IOS development: Selection of delegate, notification, and KVO

Source: Internet
Author: User
Tags notification center

IOS development: Selection of delegate, notification, and KVO

The delegate, notification, and KVO functions are similar. In actual programming, how can we choose these methods?

When developing ios applications, we often encounter a common problem: how to communicate between controllers without coupling. In IOS applications, there are three modes to achieve this communication:

1. Delegate delegation;

2. Notification Center;

3. key value observation key value observing, KVO

So, why do we need these patterns, and when to use them.

The following describes the three models based on my development experience. I will discuss why I think a certain mode is better than another mode and why I think a certain mode is better in a certain environment. The reason I have given is not the Bible, but my point of view. If you have any different points of view or can supplement them, contact me and discuss them together.

What are the above three modes?

Each of the three modes is an object that passes events to another object without coupling. The three modes are the methods for notifying an event of an object, or more accurately, they are the methods for allowing other objects to receive this event. This is a very common and necessary task for an object. Because there is no communication, controllers cannot be integrated into the entire application. Another objective of controller is to include as much as possible. We want controllers to exist in our own way and cannot be coupled with other controllers at the controllers level. Controllers can wear other controllers and can communicate freely between them, but we do not want the controller to be connected back to create its own controller. If we coupled them, we would not be able to reuse them, and completely lose control of an independent component in the application.

These three modes provide communication methods for controllers (or other objects. The following describes how to use these modes in ios apps. You also need to pay attention to the fact that they are used in other places and actually exist.

Delegation

When writing ios applications for the first time, we noticed that "delegate" is constantly used and runs throughout the SDK. The delegation mode is not unique to IOS, but depends on your past programming background. This mode may not be obvious for its advantages and why it is often used.

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 to respond to a controller event. The Protocol is the delegator, saying, "If you want to act as my delegate, you must implement these methods ". To implement these methods, the controller is allowed to call these methods in its delegate, and its delegate knows when to call the method. Delegate can be any type of object, so the controller will not be coupled with 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 syntax. All events that will be heard must be clearly defined in the delegate protocol.

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

3. the Protocol must be defined within the scope of the controller.

4. the control process in an application is traceable and identifiable;

5. You can define multiple different protocols in a controller. Each protocol has different delegates.

6. No third-party objects require the communication process to be maintained/monitored.

7. Receive the returned values of the called protocol method. This means that delegate can provide feedback to the controller.

Disadvantages:

1. A lot of code needs to be defined: 1. Protocol definition; 2. The delegate attribute of controller; 3. Implement the delegate method definition in delegate itself.

2. When releasing the proxy object, you must be careful to change the delegate to nil. Once the setting fails, the memory crash will occur when you call the method for releasing the object.

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

Notification

There is a "Notification Center" concept in IOS application development. It is a singleton object that allows some objects to be notified when an event occurs. It allows us to communicate with any object in a low degree of coupling. The basic feature of this mode is to allow other objects to receive messages generated when an event occurs in the controller. The controller uses a key (Notification name ). In this way, the controller is anonymous. Others register the notification object (I .e. the observer) with the same key to respond to the notification event.

Advantages:

1. It is easy to implement without writing much code;

2. For a notification, multiple objects can respond, that is, one-to-many implementation is simple.

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

Disadvantages:

1. during compilation, the system does not check whether the notification can be correctly handled by the observer;

2. When releasing registered objects, cancel the registration in the notification center;

3. Application work and control processes are difficult to track during debugging;

4. A third party needs to manage the relationship between the controller and the observer object;

5. The controller and the observer must know the notification name and UserInfo dictionary keys in advance. If these are not defined in the work interval, they will not be synchronized;

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

KVO

KVO is an object that can observe the attribute values of another object and detect changes in values. The first two modes are more suitable for a controller to communicate with any other objects, while KVO is more suitable for any type of objects to listen for changes to another arbitrary object (here it can also be controller, but not controller ). This is a way to synchronize an object with another object, that is, when the status of another object changes, the observed object immediately responds. It can only be used to respond to attributes, rather than methods or actions.

Advantages:

1. A simple method is provided to synchronize two objects. For example, synchronization between model and view;

2. Ability to respond to changes in the status of non-created objects, that is, internal objects, without changing the implementation of internal objects (SKD objects;

3. provides the latest and previous values of observed attributes;

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

5. Abstract The observed object, because no additional code is required to allow the observed value to be observed.

Disadvantages:

1. The observed attributes must be defined using strings. Therefore, the compiler will not receive warnings and checks;

2. refactoring of properties will make our observation Code no longer available;

3. The complex "IF" Statement requires that the object is observing multiple values. This is because all the observed code points through a method;

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

Summary:

From the above analysis, we can see that the three design modes have their own advantages and disadvantages. In fact, everything is like this. The question is how to select the right thing in a correct time environment. Next, let's talk about how to leverage their respective advantages and under what circumstances to use the mode. Note that there is no right or error when using any mode, but it is more suitable or not suitable. Each mode provides an object with a method to notify another object of an event, and the former does not need to know the listener. Among the three models, I think KVO has the clearest use cases and has a clear practicality for a specific requirement. The other two modes are similar and often used for communication between controllers. In what situations should we use one of them?

Based on my experience in developing iOS apps, I found that the notification mode is excessively used. I personally do not like to use the notification center. I found it difficult to grasp the Application Execution Process with the notification center. The keys of UserInfo dictionaries are transferred everywhere, resulting in loss of synchronization and too many constants need to be 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 too much.

I think it is easy to clearly understand communication between controllers using protocols and Protocol methods with naming rules. Efforts to define these protocol methods will enhance code readability and better track your app. The changes to the proxy protocol and implementations can be checked by the compiler. If not, at least crash will occur during the development process, not just for some exceptions. Even in scenarios where multiple controllers are notified of the same event, as long as your application has a good structure at the controller level, messages will be transmitted at that level. This level can be passed backward until all controllers who need to know the event know it.

Of course there will be exceptions that the delegation mode is not suitable for, and the notification may be more effective. For example, all controllers in an application need to know an event. However, these types of scenarios rarely appear. Another example is when you build an architecture and notify the event to the running application.

Based on experience, if it is the time of the attribute layer, whether it is a model object that requires no programming or is tightly bound to a view object, I only use observation. For other events, I will use the delegate mode. If for some reason I cannot use delegate, first I will estimate whether my app architecture has encountered a serious error. If no error occurs, 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.