Block usage and comparison (forwarding) between block and delegate, blockdelegate

Source: Internet
Author: User

Block usage and comparison (forwarding) between block and delegate, blockdelegate

I have read an article about putting block and delegate together to make it easier for everyone to understand. I recommend it to you.

The proxy design pattern is certainly very familiar to iOS developers. The proxy delegate is to delegate another object to help them complete one thing. Why do we need to entrust others to do it, this is actually a module division problem in the MVC design model. For example, a View object is only responsible for displaying the interface without data management. Data management and logic are the responsibility of the Controller, in this case, View should delegate this function to the Controller for implementation. Of course, you cannot force the View to process the data logic as a code farmer, but this is against the MVC design pattern. The small project is better. With the expansion of the function, we will find that the more difficult it is to write, the more difficult it is to write. Another situation is that it cannot be done, it can only be delegated to other objects. I will illustrate this situation in the following example.

The following code is used to implement a simple function. The scenario is described as follows: TableView has multiple mtmtableviewcells, and the cell displays text information and a detail Button, click the button and then push it to a new page. Why is delegate used in this scenario? Because the button is on the custom mtmtableviewcell, and the cell cannot implement the push function, because the code for pushing to the new page is like this,

[Self. navigationController pushViewController...];

Therefore, at this time, CustomTableViewCell will entrust its Controller to do this.

According to my coding habits, I like to write the delegated protocol in the header file of the class that puts forward the delegated application. In the current scenario, CustomTableViewCell puts forward the delegated application. Below is a simple code,

@ Protocol CustomCellDelegate <NSObject>

-(Void) pushToNewPage;

@ End

 

@ Interface CustomTableViewCell: UITableViewCell

@ Property (nonatomic, assign) id <CustomCellDelegate> delegate;

 

@ Property (nonatomic, strong) UILabel * text1Label;

@ Property (nonatomic, strong) UIButton * detailBtn;

@ End

The above code is in CustomTableViewCell. h defines a CustomCellDelegate protocol, which has a pushToNewPage method to be implemented, and then writes a property modifier named assign and delegate property, the reason for using assign is that it involves memory management. I will explain the reason in my blog later.

Next, write the Button click code in CustomTableViewCell. m,

 

[Self. detailBtn addTarget: self action: @ selector (btnClicked :) forControlEvents: UIControlEventTouchUpInside];

The corresponding btnClicked method is as follows,

-(Void) btnClicked :( UIButton *) btn

{

If (self. delegate & [self. delegaterespondsToSelector: @ selector (pushToNewPage)]) {

[Self. delegate pushToNewPage];

}

}

The condition in the code above should be written, because it is used to determine whether self. delegate is null and whether the Controller implementing the CustomCellDelegate Protocol also implements the pushToNewPage method.

The next step is the delegate application class. Here is the ViewController corresponding to CustomTableViewCell. It must first implement the CustomCellDelegate protocol and then implement the pushToNewPage method, another thing you should not forget is to set the delegate of the CustomTableViewCell object cell to be equal to self. In many cases, you may forget to write cell. delegate = self; in case of problems, you may not be confused. The following key code is in ViewController. m,

The first step is to obey the cumrentelldelegate Protocol. As we all know, it is like many system protocols, such as UIAlertViewDelegate, UITextFieldDelegate, UITableViewDelegate, and UITableViewDatasource.

@ Interface ViewController () <CustomCellDelegate>

@ Property (nonatomic, strong) NSArray * textArray;

 

@ End

Then implement the pushToNewPage method in the CustomCellDelegate protocol,

-(Void) pushToNewPage

{

DetailViewController * detailVC = [[DetailViewController alloc] init];

[Self. navigationController pushViewController: detailVC animated: YES];

}

The following code sets the delegate of the cell of the CumtomTableViewCell object,

-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath

{

Static NSString * simpleIdentify = @ "CustomCellIdentify ";

CustomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: simpleIdentify];

If (cell = nil ){

Cell = [[CustomTableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: simpleIdentify];

}

// The following code is critical.

Cell. delegate = self;

Cell. text1Label. text = [self. textArray objectAtIndex: indexPath. row];

Return cell;

}

Through cell. delegate = self; Ensure CustomTableViewCell. m judgment statement if (self. delegate &&...) self in. delegate is not empty. In this case, self. delegate is actually ViewController, and the cell object entrusts ViewController to implement the pushToNewPage method. This simple scenario describes the use of proxy, that is, CustomTableViewCell is not capable of implementing the pushViewController function, so it is delegated to ViewController.

The code can be downloaded from github.

Please correct me for any errors.

-------------------------------------------- The following is the block content ----------------------------------------------------

Block is a feature of C language. As some people in the group say, it is a function pointer of C language. The most commonly used function callback or event transfer, such as sending data to the server, wait for the server to report whether it is successful or failed. At this time, the block will be used, and the implementation of this function can also be used as a proxy. In this case, does the block feel a bit like a proxy?

I used block as a function parameter before, but I didn't quite understand it at the time. Currently, in projects, block is often used as the property, which is simpler and more straightforward. In fact, the property is not a defined variable for merging and storage, and block is also a defined variable as a function parameter, therefore, there is no difference as a function parameter or as a property.

Let's take a look at the block syntax summarized by others, http://fuckingblocksyntax.com, this link is bright, fucking block syntax, the block syntax of the egg. Block has the following usage situations,

1. As a local variable)

ReturnType (^ blockName) (parameterTypes) = ^ returnType (parameters ){...};

2. As @ property

@ Property (nonatomic, copy) returnType (^ blockName) (parameterTypes );

3. method parameter)

-(Void) someMethodThatTakesABlock :( returnType (^) (parameterTypes) blockName;

4. called as a method parameter

[SomeObject someMethodThatTakesABlock: ^ returnType (parameters) {...}];

5. Using typedef to define a block can get twice the result with half the effort

Typedef returnType (^ TypeName) (parameterTypes );
TypeName blockName = ^ returnType (parameters ){...};

I copied and pasted the above, and then clicked the Button above CustomTableViewCell to implement the page Jump function. I used to compare block to delegate more than once, and I am also thinking inertia here, the following content is used as a proxy. Some Terms are similar to delegate. First, define the block property in CustomTableViewCell,

@ Interface CustomTableViewCell: UITableViewCell

@ Property (nonatomic, strong) UILabel * text1Label;

@ Property (nonatomic, strong) UIButton * detailBtn;

 

// The following definition is for reference.

/* I DID NOT delete the delegate definition, because you can look at it like this */

@ Property (nonatomic, assign) id <CustomCellDelegate> delegate;

/* ButtonBlock is defined here */

@ Property (nonatomic, copy) void (^ ButtonBlock )();

@ End

Here we use the copy attribute to modify the ButtonBlock property. For this reason, I will explain it in my blog later.

Next, in CustomTableViewCell, bind the click method to the detailBtn above it,

[Self. detailBtn addTarget: self action: @ selector (btnClicked :) forControlEvents: UIControlEventTouchUpInside];

Then there is the details of the btnClicked method. I have not deleted the delegate content, that is, I will compare the features and syntaxes of the block and delegate,

-(Void) btnClicked :( UIButton *) btn

{

// This is the previous delegate

If (self. delegate & [self. delegate respondsToSelector: @ selector (pushToNewPage)]) {

[Self. delegate pushToNewPage];

}

// This is the block we want to talk about now.

If (ButtonBlock ){

ButtonBlock ();

}

}

The following is a key point. In ViewController2, set the ButtonBlock of the cell Object of CustomTableViewCell, that is, assign a value to it. Here I still keep the cell. delegate = self; code,

-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath

{

NSString * blockIdentify = @ "BlockIdentify ";

CustomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: blockIdentify];

If (cell = nil ){

Cell = [[CustomTableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: blockIdentify];

}

Cell. text1Label. text = [self. textArray objectAtIndex: indexPath. row];

// Delegate's indispensable code, which is put here to give you an analogy

Cell. delegate = self;

// Indispensable code of ButtonBlock

Cell. ButtonBlock = ^ {

[Self pushToNewPage2];

};

Return cell;

}

Cell. ButtonBlock =^{}; is assigned a value because we define ButtonBlock in this way. void (^ ButtonBLock) () indicates that no return value has no parameters.

Then write the pushToNewPage2 method,

-(Void) pushToNewPage2

{

DetailViewController * detailVC = [[DetailViewController alloc] init];

[Self. navigationController pushViewController: detailVC animated: YES];

}

Check whether this method is similar to the pushToNewPage method in the CustomCellDelegate protocol. Then, let's look back at the analogy. Is block a lite version of delegate? Because the delegate design mode requires the CustomCellDelegate protocol, and cell may be omitted easily. delegate = self; but the block is much easier to use.

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.