OC tutorial 5-delegate mode callback

Source: Internet
Author: User

OC tutorial 5-delegate mode callback
OC5-delegate mode callback

This chapter describes the callback interfaces that have been implemented in the delegate mode.

1. Delegation Mode

Delegation mode is a development mode exclusive to OC syntax. It is a rapid development mode based on component assembly. This mode ensures high flexibility and versatility of components. It is an open interface of components.

The following describes the application of delegated mode in a real-life scenario.

For example, we have a company. The company wants an IPO. However, the company's boss is not familiar with capital operations. At this time, it is necessary to entrust a person or an organization to do this.

First, the company must put forward detailed requirements for IPO, and then find the right candidates through the headhunting.

The code description should be as follows:

  • First, describe the company's employment requirements using the agreement
  • Declare an attribute that complies with the protocol. This attribute should be assigned by the outside world, such as the headhunting company.
  • When a company wants to go public, it will essentially follow the agreement of onePerson to do this. It doesn't matter who is onePerson. What's important is that he has a way to go public.
    // Company's employment agreement @ protocol CompanyProtocol
        
         
    -(Void) doIPO; @ end // Company class declaration @ interface Company: NSObject @ property (nonatomic, strong) id
         
          
    OnePerson;-(void) stratIPO; @ end // implementation of the Company class @ implementation Company-(void) stratIPO {if (self. onePerson) {[self. onePerson doIPO] ;}}@ end
         
        

    The company's declaration code has an attribute. This mode is similar to the composite development mode, but essentially different.

    We analyze the advanced air conditioners developed through the composite mode. When preparing for the development of advanced air conditioners, the formaldehyde removal module already exists. All the modules directly declare a formaldehyde removal attribute and allocate memory for this attribute during initialization, in this way, the air conditioner can have the formaldehyde removal function.

    But when describing the company, we don't know who can lead the company to perform an IPO, but we can't stop the entire company because the candidates for a person's position are not determined. All the methods of delegation are used to outsource the case. The company does not care about the specific object, but whether the relationship can be completed.

    Next, let's create an object that can complete the listing operation and let it help the company complete the listing task.

    @ Interface Finance: NSObject
        
         
    @ End @ implementation Finance-(void) doIPO {NSLog (@ "start listing! ");} @ End
        

    Now the company and people who can lead the company are all complete, so we can proceed with the next development.

    Main () {Finance * per = [[Finance alloc] init]; Company * company = [[Company alloc] init]; company. onePerson = per; [company startIPO]; // when the company starts an IPO, it essentially calls the doIPO method of the Finance object per .}

    Although from the code above, it is the company's IPO, but the essence of development is that the company entrusts per object for IPO operations. This mode is the delegate mode.

    2. Delegate callback

    The implementation of the delegated mode is complex and needs to be designed based on actual application scenarios. However, we will not use much of it later. Just make it easy to understand here.

    The delegate callback mode is an event feedback interface encapsulation Based on the delegate mode.

    The switch in the previous chapter is used as an example. In the previous chapter, we already know the concept of callback and the meaning of callback. The core is to allow the component status to be promptly reported to the user. In the target action mode, you can configure the callback object and callback method of the component to monitor the status of the component.

    In this chapter, the delegate callback mode monitors the component status by setting the principal of the component and implementing the delegate method.

    Delegated (agent) Person: from the example listed in the document, we can see that the company entrusts financial personnel to perform the listing operation. Therefore, from the company's perspective, financial personnel are the company's principal. In the case of listing, financial personnel are representatives of the company, also known as agents. The principal and the agent are essentially different descriptions of the same object from different perspectives.

    Delegate (proxy) method: the company uses an agreement to declare the actions of the principal. As the company's principal, of course, these actions must be carried out. The method stated in the agreement is a delegate method from the company perspective, and a proxy method from the financial personnel perspective.

    Generally, a component needs to submit its status information through delegation. To monitor the component Status, you only need to act as the Principal of the component and implement the delegate method.

    Next we will use the switch as an example to explain the code.

    • Read the Declaration file of the switch to determine the principal attributes and delegate Methods
    • Use the switch as a component of the room, declare the property and allocate memory.
    • Set the principal of the switch and implement the delegate Method

      Switch declaration File

      @ Protocol SwitchDelegate; // Forward Declaration, inform the compiler SwitchDelegate as a protocol @ interface SwitchD: NSObjecttypedef enum: NSUInteger {SwitchStateOff, // default SwitchStateOn,} SwitchState; @ property (nonatomic, assign, readonly) SwitchState currentState; @ property (nonatomic, weak) id
            
             
      Delegate; @ end @ protocol SwitchDelegate
             
              
      // When the switch status changes, this method of the principal is called for Status feedback. -(Void) switchD :( SwitchD *) s didChangeState :( SwitchState) currentState; @ end
             
            

      Room declaration file. h

      @interface Room : NSObject 
            
             @end
            

      Room implementation file. m

      @ Interface Room ()
            
             
      @ Property (strong, nonatomic) Light * aLight; @ property (strong, nonatomic) SwitchD * aSwitch; @ end @ implementation Room-(instancetype) init {self = [super init]; if (self) {self. aLight = [[Light alloc] init]; self. aSwitch = [[SwitchD alloc] init]; // set the principal of the switch as self (Room object. aSwitch. delegate = self;} return self;}-(void) switchD :( SwitchD *) s didChangeState :( SwitchState) currentState {if (currentState = SwitchStateOff) {[self. aLight turnOff];} else {[self. aLight turnOn] ;}}@ end
            

      The code above shows that when the switch status changes, the switch object will call the delegate method implemented by the Room. The internal code of the delegate method is used to process the feedback on the switch status.

      3. Delegate callback and target action callback

      Now we have come into use two callback modes. Here we will explain the differences and use cases.

      The target action callback is a status callback of a simple component. It features flexibility and allows users to customize their own callback methods, but this is also a disadvantage of the target action callback. Since you can specify the callback method by yourself, you cannot explicitly declare the callback parameters during callback. All, the target action callback usually has a parameter, that is, the object that triggers the callback method. Other parameters need to be obtained through the attributes of the object.

      Delegate mode callback is a complex component callback. The callback method is declared by the Protocol in advance. All event callbacks that can specify their callback parameters are suitable for carrying parameters. During App development, common events carry parameters. Therefore, components with delegate callback mode interfaces are more common.

      However, delegate callback also has its own shortcomings, that is, if a class has two components of the same type at the same time. The callback methods of these two components are the same. We need to determine in the method which component calls back the delegate method. Independent callback for each component cannot be implemented. In the code block callback in the next chapter, this problem is perfectly solved.

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.