IOS design mode-delegate)

Source: Internet
Author: User
Tags string back

A delegate is also called a proxy, which is a common design pattern in iOS development. With Protocol (refer to the blog post: Objective-C protocol), we can easily implement this design mode.

What is proxy?

Apple's official documentation provides a clear explanation:

Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another
Object. the delegating object keeps a reference to the other object-the Delegate-and at the appropriate time sends a message to it. the message informs the delegate of an event that the delegating object is about to handle or has just handled. the delegate
May respond to the message by updating the appearance or state of itself or other objects in the application, and in some cases it can return a value that affects how an impending event is handled. the main value of delegation is that it allows you to easily
Customize the behavior of several objects in one central object.

Proxy is a simple and powerful design mode. This mode is used to "represent" another object and interact with other objects in the program. The master object (this refers to the delegating object) maintains a reference of a proxy (delegate) and sends a message to the proxy when appropriate. This message notifies the "proxy" that the main object is about to process or that an event has been processed. This proxy can respond to the message of the event sent by the primary object by updating the UI interface of itself or other objects or other States. Or, in some cases, a value can be returned to affect how other upcoming events are handled. The main value of proxy is that it allows you to easily customize the behavior of various objects. Note that the proxy here is a noun, and it is an object. This object specifically represents the proxy object to deal with other objects in the program.


Proxy in cocoa

The cocoa touch framework uses a large number of proxy design patterns. In each UI control class, a delegate or datasource with the ID type is declared, you can view the header file of cocoa and find many of the following attributes:

@ Property (nonatomic, assign) ID <uiactionsheetdelegate> delegate; // weak reference

Generally, the format is @ property (nonatomic, assign) ID <protocol_name> delegate; that is, the proxy must follow a certain protocol, that is, only class objects that follow this Protocol are eligible for proxy. This also requires that the proxy class must declare in the header file to follow the protocol_name Protocol and implement the @ required method. The @ optional method is optional.

Taking uiactionsheet as an example, we define a view. When a button in this view is clicked, The uiactionsheet is triggered. When a user completes an operation on the uiactionsheet, for example, the destruct button is pressed, or when the cancel button is pressed, uiactionsheet sends a message to delegate, and the delegate completes the response to user operations, such as printing a string to the screen. The illustration is as follows:

First, create a tab-based project and add code in firstviewcontroller. h to make this class conform to the uiactionsheetdelegate protocol:

@interface FirstViewController : UIViewController <UIActionSheetDelegate>

Add a button in the view to trigger this actionsheet, and then write the response code for this button:

- (IBAction)invokeActionSheet:(id)sender {        UIActionSheet *actionSheet = [[UIActionSheet alloc]                                  initWithTitle:@"Delegate Example"                                  delegate:self // telling this class(ViewController) to implement UIActionSheetDelegate                                  cancelButtonTitle:@"Cancel"                                  destructiveButtonTitle:@"Destruct"                                  otherButtonTitles:@"Button 1",@"Button 2",nil];        [actionSheet showInView:self.tabBarController.view];    [actionSheet release];}

Note that the preceding important setting is that the parameter has a delegate: self, which indicates that the proxy of the uiactionsheet is self, that is, firstviewcontroller.

Then implement the method in uiactionsheetdelegate in firstviewcontroller. M:

#pragma mark --UIActionSheet delegate methods- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {    switch (buttonIndex) {        case 0:            self.myTextFromActionSheet.text = @"Action Destructed!";            break;        case 1:            self.myTextFromActionSheet.text = @"Action Button 1 Clicked!";            break;        case 2:            self.myTextFromActionSheet.text = @"Action Button 2 Clicked!";            break;        case 3:            self.myTextFromActionSheet.text = @"Cancel Button Clicked!";            break;        default:            break;    }    }

In the preceding steps, we have used the existing proxy of uiactionsheet in cocoa. However, we often need to write our own custom proxies. How can we achieve this?

Custom proxy

What we need to do is to create a view and customize a proxy to update the strings in this view. We have created a tab project and borrowed the second view from it. We drag a button and name it changetext, and the response function is-(ibaction) changetext :( ID) sender. Click this button to enter a modal view named changetextview, we enter a string in changetextview and update the string to second after exiting this view.
View. How can we transmit data between modal view and second view? That's the proxy! Who is the proxy? Changetextview proxy! Because we directly input data in changetextview, the agent needs to feed the input string back to second view.

1. Create a new class changetextviewcontroller and a corresponding XIB file.

2. Declare the changetextviewdelegate protocol in changetextviewcontroller. h:

@protocol ChangeTextViewDelegate <NSObject>- (void) textEntered:(NSString*) text;@end

Like uiactionsheet, we also need to add a proxy declaration in changetextviewcontroller:

@property (assign, nonatomic) id<ChangeTextViewDelegate> delegate;

3. You also need to add a Save button in changetextviewcontroller. XIB. When you press this button, it will return to second view and update the string. The response function for the Save button is:

- (IBAction)saveButtonClicked:(id)sender {    //Is anyone listening    if([delegate respondsToSelector:@selector(textEntered:)])    {        //send the delegate function with the amount entered by the user        [delegate textEntered:textEntered.text];    }        [self dismissModalViewControllerAnimated:YES];}

[Delegate textentered: textentered. text]; the meaning of the Code is the changetextviewcontroller notification proxy. The textentered event occurs. The implementation of the message textentered, that is, how to respond to the textentered event, is implemented by the proxy. In this example, secondviewcontroller is the proxy of the changetextviewcontroller object. Therefore, we need to set secondviewcontroller to meet the proxy conditions. First, declare the Compliance Protocol changetextviewdelegate in secondviewcontroller. h. Then edit the response function of the changetext button-
(Ibaction) changetext :( ID) sender;

- (IBAction)changeText:(id)sender {    ChangeTextViewController *CTViewController = [[ChangeTextViewController alloc] initWithNibName:@"ChangeTextViewController" bundle:nil];    //Assign this class to the delegate of ChangeTextViewController,    //remember to make thie ViewController confirm to protocol "ChangeTextViewDelegate"    //which is delared in file ChangeTextViewController.h    CTViewController.delegate = self;    [self presentModalViewController:CTViewController animated:YES];}

Note: ctviewcontroller. Delegate = self; this sentence enables secondviewcontroller to become the proxy of the changetextviewcontroller object.

Download the corresponding source code: http://download.csdn.net/detail/lovefqing/4874331

If there are any mistakes in this article, please correct them and make progress together. Thank you!

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.