Analysis of delegate in Objective-c

Source: Internet
Author: User

Delegate

In ios development, we often use a dialog box similar to the following:


Therefore, we are very familiar with the following code:

-(IBAction) showSheet :( id) sender {UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle: @ "title," delegate: self cancelButtonTitle: @ "cancel" destructiveButtonTitle: @ "OK" otherButtonTitles: @ "first", @ "second", nil]; actionSheet. actionSheetStyle = UIActionSheetStyleBlackOpaque; [actionSheet showInView: self. view];}
The second parameter of the initWithTitle function is delegate. What is it? Let's see it in its header file. The Declaration of the initWithTitle function is as follows:

- (id)initWithTitle:(NSString *)title delegate:(id
 
  )delegate cancelButtonTitle:(NSString *)cancelButtonTitle destructiveButtonTitle:(NSString *)destructiveButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION;
 
Yes, the above huge function declaration is the initWithTitile function. The oc language itself makes me feel complicated. We can see that the delegate parameter type is id. To view the declaration of UIActionSheetDelegate:

@protocol UIActionSheetDelegate 
  
   @optional// Called when a button is clicked. The view will be automatically dismissed after this call returns- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex;// Called when we cancel a view (eg. the user clicks the Home button). This is not called when the user clicks the cancel button.// If not defined in the delegate, we simulate a click in the cancel button- (void)actionSheetCancel:(UIActionSheet *)actionSheet;- (void)willPresentActionSheet:(UIActionSheet *)actionSheet;  // before animation and showing view- (void)didPresentActionSheet:(UIActionSheet *)actionSheet;  // after animation- (void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex; // before animation and hiding view- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex;  // after animation@end
  
We can see that UIActionSheetDelegate is a common protocol. There are six functions under @ optional. These functions are optional. Each function corresponds to the Click Event Processing of each button in UIActionSheet, of course, the last two functions differentiate Button Objects Based on indexes.

Implementation of delagate

The protocol and delegate are not the same concept. The protocol is a language-level feature, while the delegate is a design mode implemented by the protocol, which is actually a proxy mode. Inject proxy objects to implement corresponding functions. In fact, its main function is to implement callback, just like listener in Java.

The following is an example:

// ButtonClickDelegate protocol @ protocol ButtonClickDelegate
  
   
-(Void) onClick: (id) sender; @ end // view declaration, implementing the ButtonClickDelegate Protocol @ interface UIView: NSObject
   
    
{@ Protected id
    
     
ClickDelegate;} // Click Event proxy. Therefore, UIView implements the ButtonClickDelegate protocol, so you can proxy yourself. @ Property (nonatomic, strong) id
     
      
ClickDelegate; // click the view trigger function-(void) initialize mclick; @ end // view implementation @ implementation UIView @ synthesize clickDelegate; // default Click Event-(id) init {self = [super init]; if (self) {clickDelegate = self;} return self;} // default processing of click view events-(void) onClick: (id) sender {NSLog (@ "click the default processing function of view. ");} // Click Event-(void) javasmclick {[clickDelegate onClick: self];} @ end // ViewController declaration, implements the ButtonClickDelegate protocol, can be used as a proxy for UIView @ interface ViewController: NSObject
      
       
@ Property (nonatomic, strong) UIView * parenView; @ end // ViewController implementation @ implementation ViewController-(void) onClick :( id) sender {NSLog (@ "ViewController to implement Click Event");} @ end
      
     
    
   
  
Main function:

// Mainint main (int argc, const char * argv []) {@ autoreleasepool {// view object UIView * view = [[UIView alloc] init]; [view multiple mclick]; // construct a ViewController object ViewController * controller = [[ViewController alloc] init]; view. clickDelegate = controller; [view multiple mclick];} return 0 ;}

First, create a UIView object view and call the receivmclick function. In this case, the view does not set delegate. However, because you have implemented the ButtonClickDelegate protocol, you can proxy the click event for yourself. Then, we create the ViewController object controller, set this object as the view object's delegate, and then execute the optimize mclick function. In this case

The onClick function in ViewController is executed, that is, the controller processes the view click event. The output result is as follows:

Click the default processing function of view. ViewController to implement click events.

Delegate and Listener in Java

The delegate function is similar to the Listener function in Java. For example, let's look at how to process the Click Event of a button in Android.

ButtonmJumpButton = (Button) findViewById(R.id.button_jump);mJumpButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent(MainActivity.this,SecondActivity.class);startActivity(intent);}});

The Button is equivalent to the UIView mentioned above, and its setOnClickListener is equivalent to the setting method of the delegate attribute. OnClickListener plays the role of ButtonClickDelegate in the previous article,

The onClick method is exactly the same. In fact, the design ideas of each platform are similar in general. It is easier to observe the comparison and implementation of different platforms.


The delegate and id types are declared as follows:

// Click Event proxy, so UIView implements the ButtonClickDelegate protocol, so you can proxy for yourself. @ Property (nonatomic, strong) id
  
   
ClickDelegate;
  

Note that the type here is id ; This indicates that the delegate object can be of any type, but this type must implement ButtonClickDelegate Protocol,It can also be said that this type must adopt the formal protocol ButtonClickDelegate. This is similar to the generic type in Java. For example, we can use the generic type in Java,

void setData(List
   myorders) ;
The parameters accepted in the setData function are the List set of the element type as the Order subclass Is it very similar?

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.