IOS delegation Mode

Source: Internet
Author: User

 



Delegated Delegate is a protocol. It is implemented by @ protocol. As the name suggests, it is to entrust others to do something for themselves. That is, when it is not convenient for you to do anything, you can establish a delegate so that you can entrust others to help you implement what methods.

I briefly summarized two functions of the delegate I used: value transfer and event transfer. 1. The so-called value transfer is often used in Class B to pass one of its own data or objects to Class A for Class A to be displayed or processed. (This function is particularly useful when passing parameters between two View views) (Example 1) 2. the so-called transfer event is what happened to Class A. Tell the person who pays attention to the event, that is, the delegate object, it is the delegate object to consider what reflection should be made after this event occurs. Simply put, if A Class A has an event, it does not come out, but is in the form of delegate, let its delegate Object Class B be processed (of course, delegate object B must implement the delegate method ). (Example 2) ---- examples are shown below. You must pay attention to some issues during the process of delegation: 1. The protocol @ protocol needs to be defined during the delegation process. This protocol can be used to separate New files into a separate protocol File, it can also be placed in the header file of the delegate object. The general habit is the latter. 2. Define some methods in the Protocol that the delegate object needs to delegate to others for processing, and use them to transmit values or events. 3. Define an instance object for the protocol in the delegate class. Note that the attribute is generally set to assign rather than retain (generally named delegate, but note that if this attribute is originally set for the class, you need to change the name). Through this protocol instance object, you can call methods in the Protocol (that is, delegate methods ). 4. In the delegated class, you must declare the Protocol in the interface: <XXXDelegate>, indicating that the class must implement methods in the XXXDelegate protocol. 5. Pay attention to setting the delegate of the delegate class object as the delegate Class Object. There are two methods to deal with it: ① delegate Class Object. delegate = delegate class object. ② Define a delegate class object in the delegated class, and set the delegate Class Object. delegate = self (Example 3). Here are three demo examples to give a more vivid experience. I. a brief example of the delegated value passing is as follows: the delegate class is Customer, and a method is defined in the delegate protocol, this method indicates that the customer wants to buy an iphone (an iphone model parameter will be passed), and the customer calls this method by entrusting the delegate method to indicate that the customer wants to buy an iphone. The delegated class is Businessman. It inherits this protocol and implements the methods in the protocol, that is, it handles the Needs of the delegated class customers who want to buy the iphone. Post Code below: Customer. h [cpp] # import <Foundation/Foundation. h> @ protocol MyDelegate <NSObject>-(void) buyIphone :( NSString *) iphoneType; @ end @ interface Customer: NSObject @ property (nonatomic, assign) id <MyDelegate> delegate; -(void) willBuy; @ end # import <Foundation/Foundation. h> @ protocol MyDelegate <NSObject>-(void) buyIphone :( NSString *) iphoneType; @ end @ interface Customer: NSObject @ property (nonatomic, Assign) id <MyDelegate> delegate;-(void) willBuy; @ endCustomer. m [cpp] # import "Customer. h "@ implementation Customer @ synthesize delegate;-(void) willBuy {[delegate buyIphone: @" Iphone5 "] ;}@ end # import" Customer. h "@ implementation Customer @ synthesize delegate;-(void) willBuy {[delegate buyIphone: @" Iphone5 "] ;}@ endBusinessman. h [cpp] # import <Foundation/Foundation. h> # import "Customer. h "@ interf Ace Businessman: NSObject <MyDelegate> @ end # import <Foundation/Foundation. h> # import "Customer. h "@ interface Businessman: NSObject <MyDelegate> @ endBusinessman. m [cpp] # import "Businessman. h "@ implementation Businessman-(void) buyIphone :( NSString *) iphoneType {NSLog (@" There is an Iphone store, we have % @ ", iphoneType );} @ end # import "Businessman. h "@ implementation Businessman-(void) buyIphone :( NSS Tring *) iphoneType {NSLog (@ "There is an Iphone store, we have % @", iphoneType);} @ endmain. m [cpp] # import <Foundation/Foundation. h> # import "Customer. h "# import" Businessman. h "int main (int argc, const char * argv []) {@ autoreleasepool {// insert code here... customer * customer = [[Customer alloc] init]; Businessman * businessman = [[Businessman alloc] init]; customer. delegate = businessman; [custome R willBuy];} return 0;} # import <Foundation/Foundation. h> # import "Customer. h "# import" Businessman. h "int main (int argc, const char * argv []) {@ autoreleasepool {// insert code here... customer * customer = [[Customer alloc] init]; Businessman * businessman = [[Businessman alloc] init]; customer. delegate = businessman; [customer willBuy];} return 0;} 2. The following is an example of a delegate event: boss: he's working on drafting documents and answering phone calls. But he does not implement the response methods of these events. Instead, he uses the delegate class to implement the response methods. Delegated class: Secretary is entrusted by the Boss to draft documents and answer telephone tasks. Post Code below: Boss. h [cpp] # import <Foundation/Foundation. h> @ protocol MissionDelegate <NSObject>-(void) draftDocuments;-(void) tellPhone; @ end @ interface Boss: NSObject @ property (nonatomic, assign) id <MissionDelegate> delegate; -(void) manage; @ end # import <Foundation/Foundation. h> @ protocol MissionDelegate <NSObject>-(void) draftsponents;-(void) tellPhone; @ end @ interface Boss: NSObject @ property (nona Tomic, assign) id <MissionDelegate> delegate;-(void) manage; @ endBoss. m [cpp] # import "Boss. h "@ implementation Boss @ synthesize delegate = _ delegate;-(void) manage {[_ delegate draftents]; [_ delegate tellPhone];} @ end # import" Boss. h "@ implementation Boss @ synthesize delegate = _ delegate;-(void) manage {[_ delegate draftDocuments]; [_ delegate tellPhone];} @ endSecretary. h [cpp] # import <Foundatio N/Foundation. h> # import "Boss. h "@ interface Secretary: NSObject <MissionDelegate> @ end # import <Foundation/Foundation. h> # import "Boss. h "@ interface Secretary: NSObject <MissionDelegate> @ endSecretary. m [cpp] # import "Secretary. h "@ implementation Secretary-(void) draftDocuments {NSLog (@" Secretary draft documents ");}-(void) tellPhone {NSLog (@" Secretary tell phone ");} @ end # import "Secretary. h" @ Implementation Secretary-(void) draftDocuments {NSLog (@ "Secretary draft documents");}-(void) tellPhone {NSLog (@ "Secretary tell phone");} @ endmain. m [cpp] # import <Foundation/Foundation. h> # import "Secretary. h "# import" Boss. h "int main (int argc, const char * argv []) {@ autoreleasepool {// insert code here... boss * boss = [[Boss alloc] init]; Secretary * secretary = [[Secretary alloc] init]; bos S. delegate = secretary; [boss manage];} return 0 ;}# import <Foundation/Foundation. h> # import "Secretary. h "# import" Boss. h "int main (int argc, const char * argv []) {@ autoreleasepool {// insert code here... boss * boss = [[Boss alloc] init]; Secretary * secretary = [[Secretary alloc] init]; boss. delegate = secretary; [boss manage];} return 0;} 3. In this example, a MyView class is defined by passing parameters between two view views. A button, butto N event response is not handled by the delegate class, so it is the delegate class. In the main view, add an Instance Object of the MyView class and set the proxy of this instance object to self, so it is the delegate class. The code below should be easy to understand. MyView. h [cpp] # import <UIKit/UIKit. h> @ protocol MyDelegate <NSObject>-(void) print :( NSString *) viewName; @ end @ interface MyView: UIView @ property (nonatomic, assign) id <MyDelegate> mydelegate; @ end # import <UIKit/UIKit. h> @ protocol MyDelegate <NSObject>-(void) print :( NSString *) viewName; @ end @ interface MyView: UIView @ property (nonatomic, assign) id <MyDelegate> mydelegate; @ endMyView. m [cpp] # import "MyView. h "@ implementation MyView @ synthesize mydelegate = _ mydelegate;-(id) initWithFrame :( CGRect) frame {self = [super initWithFrame: frame]; if (self) {// Code creates a button UIButton * button = [UIButton buttonWithType: UIButtonTypeRoundedRect]; [button setTitle: @ "Button" forState: UIControlStateNormal]; [button setFrame: CGRectMake (10, 10,100, 50)]; [button setTintColor: [UIColor blueColor]; // in Target-Action mode, the target of the event processing object specified by the button is self, the event processing method is buttonPressed [button addTarget: self action: @ selector (buttonPressed) forControlEvents: UIControlEventTouchUpInside]; [self addSubview: button];} return self ;} // response method for event processing-(void) buttonPressed {[_ mydelegate print: @ "this is a view"] ;}@ end # import "MyView. h "@ implementation MyView @ synthesize mydelegate = _ mydelegate;-(id) initWithFrame :( CGRect) frame {self = [super initWithFrame: frame]; if (self) {// Code creates a button UIButton * button = [UIButton buttonWithType: UIButtonTypeRoundedRect]; [button setTitle: @ "Button" forState: UIControlStateNormal]; [button setFrame: CGRectMake (10, 10,100, 50)]; [button setTintColor: [UIColor blueColor]; // in Target-Action mode, the target of the event processing object specified by the button is self, the event processing method is buttonPressed [button addTarget: self action: @ selector (buttonPressed) forControlEvents: UIControlEventTouchUpInside]; [self addSubview: button];} return self ;} // response method for event processing-(void) buttonPressed {[_ mydelegate print: @ "this is a view"] ;}@ endDelegateViewController. h [cpp] # import <UIKit/UIKit. h> # import "MyView. h "@ interface DelegateViewController: UIViewController <MyDelegate> @ end # import <UIKit/UIKit. h> # import "MyView. h "@ interface DelegateViewController: UIViewController <MyDelegate> @ endDelegateViewController. m [cpp] # import "DelegateViewController. h "@ interface DelegateViewController () @ end @ implementation DelegateViewController-(id) initWithNibName :( NSString *) bundle :( NSBundle *) handle {self = [super initWithNibName: bundle: nibBundleOrNil]; if (self) {// Custom initialization} return self;}-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view. mySQL view * MyView = [[myView alloc] initWithFrame: CGRectMake (50,100,200,100)]; [MyView setBackgroundColor: [UIColor yellowColor]; myView. mydelegate = self; [self. view addSubview: myView];}-(void) print :( NSString *) viewName {NSLog (@ "% @", viewName);}-(void) didReceiveMemoryWarning {[super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated .} @ end

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.