IOS development-use delegate for message transmission

Source: Internet
Author: User

IOS development-use delegate for message transmission

In iOS development, passing messages or data between interfaces is the most basic requirement. We can use many methods to achieve this requirement, for example, expose an attribute in the header file, such as using notification. Today, we will introduce another Method: Using delegate to transmit messages.

Delegate is also a proxy design mode. Using delegation avoids high coupling between classes. The delegated assignment is more secure and controllable. You can assign values to yourself without exposing the attributes of your class.

In iOS, delegation is implemented through the protocol @ protocol. Methods declared in the protocol do not need to be implemented in the protocol, is implemented by its implementation class (this class must include the <protocol name> in the header file ). "Protocol" and "delegate" are two different concepts, because we always see them together when we look at the code. But it cannot be said that delegate is protocol, and delegate is an architecture model. For example, what is "Commission"? For example, if I am driving but cannot watch text messages, I ask a friend in the car to help me read the text message so that I can drive normally. After reading the text message, a friend will tell me what it is. This is the delegate, and my friend is the delegate object. The "protocol" protocol is used to define the attributes and behaviors of objects, similar to virtual functions in C ++. There are two keywords @ required and @ optional. The former indicates the method that must be implemented, and the latter is an optional method.

Delegate is commonly used in two scenarios:

* Value transfer between two classes. Class A calls the method of Class B, and Class B encounters A problem during execution. Class A is notified;

* The value transfer between the Controller (ViewController) and the controller (ViewController) will jump from A to B, and then notify A to update the UI or do other things when B returns to, at this time, we use the proxy (delegate) to pass the value.

Tips: If @ required or @ optional is not explicitly written in @ protocol, @ required (required) is used by default. To avoid ambiguity, it is best to explicitly write @ required or @ optional.

Generally, the process of using a delegate takes five steps:

(1) create a delegate;

(2) The delegate declares a delegate;

(3) The delegate calls the method in delegate );

(4) set a delegate for the delegated user to be called by the entrusting user;

(5) the method defined by the delegate to implement the delegate;

Below I demonstrate using a single instance to pass data using delegate, the code is uploaded to: Delegate01.

(1) first, the program is built based on the storyboard. The interface layout is as follows: data will be transmitted when the interface returns.

.

 

(2) create a new Protocol as our Protocol, which can declare some methods.

.

 

 

The implementation in ProtocolDelegate is as follows:

 

# Import
 
  
// Implement a protocol;/*** can be understood as an interface in Java; */@ protocol ProtocolDelegate
  
   
// Required method @ required-(void) execute; // optional method @ optional-(void) function1;-(void) function2;-(void) function3; @ end
  
 


 

(3) I will first implement the second interface, in the header file of the second interface. h, you need to declare a protocol. The methods declared in the protocol can be implemented on the first interface and called on the second interface. This is the key to data transmission.

 

# Import
 
  
// Create a new Protocol. The Protocol name is generally implemented by the method declared in the Protocol by "class name + Delegate"/*** on the first interface, call this interface. */@ protocol ViewControllerBDelegate
  
   
@ Required-(void) sendValue :( NSString *) value; @ end @ interface ViewControllerB: UIViewController // The delegate here should be set in. h; @ property (weak, nonatomic) id
   
    
Delegate; @ end
   
  
 

(4) implement the following in the implementation file of the Second Interface: Call the method in the protocol when you click the return key,

 

 

# Import "ViewControllerB. h "// second interface; @ interface ViewControllerB () @ property (strong, nonatomic) IBOutlet UITextField * textField; @ end @ implementation ViewControllerB-(IBAction) backAction :( id) sender {// call this method when the interface is redirected; [self. delegate sendValue: self. textField. text]; // notification execution protocol method // return message transmission; [self. navigationController popViewControllerAnimated: YES];} @ end

(5) The first page ViewController. m is implemented below:

 

 

# Import "ViewController. h" # import "ProtocolDelegate. h" # import "ViewControllerB. h" // The first interface; @ interface ViewController ()
 
  
@ End @ implementation ViewController // This method is automatically called back when the interface is redirected because it is built based on the storyboard seue.-(void) prepareforseue :( UIStoryboardSegue *) seue sender :( id) sender {ViewControllerB * vc = segue. destinationViewController; [vc setDelegate: self];} // here the Protocol method for implementing controller B-(void) sendValue :( NSString *) value {UIAlertView * alertView = [[UIAlertView alloc] initWithTitle: @ "success" message: value delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil, nil]; [alertView show];} // This method is the @ required method in ProtocolDelegate;-(void) execute {}-(IBAction) pressed :( id) sender {NSLog (@ "1111");} @ end
 

(6) The running effect is as follows:

 

.

 

.

 

The demo above is based on storyboard. Because some projects are built based on the nib file, I will demonstrate the notes when using the nib file.

(1) Delete the original main. storyboard, add two nib files, and bind the corresponding ViewController. I recommend using navigationBar, so the implementation in AppDelegate. m is as follows:

 

#import "AppDelegate.h"#import "ViewController.h"@interface AppDelegate ()@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];  self.window.rootViewController = [[ViewController alloc] init];  self.naviController = [[UINavigationController alloc] initWithRootViewController:self.window.rootViewController];  [self.window addSubview:self.naviController.view];  [self.window makeKeyAndVisible];  return YES;}@end

(2) In the second interface, modify the following to delete the prepareForSegue method and click the button to implement the method:

 

 

-(IBAction) pressed :( id) sender {// if the project itself is built based on the nib file, bind the delegate in the following way and jump to it; viewControllerB * vb = [[ViewControllerB alloc] initWithNibName: @ "ViewControllerB" bundle: [NSBundle mainBundle]; vb. delegate = self; [self. navigationController pushViewController: vb animated: true];}

 

Then, the running effect is the same as the preceding one. The difference is that the delegate bound to ViewController is different.

 

In summary, the Delegate delegation belongs to the program architecture level and is a relatively high level. If we are proficient in using delegate, we can effectively reduce the program coupling and improve code readability .!

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.