Block is simple, just like delegate's simplified version.

Source: Internet
Author: User

Proxy design mode for iOS developers must be very familiar with, agent delegate is to delegate another object to help accomplish one thing, why entrust others to do, this is actually the MVC design pattern of the module division of labor, such as the View object it is only responsible for the display interface, Without the need for data management, data management and logic is the controller's responsibility, so at this point the view should be entrusted to the Controller to implement, of course, you as a code farmer forced to view the task of processing data logic, it is not impossible, Just this violates the MVC design pattern, the project is small OK, with the expansion of the function, we will find that the more written the more difficult to write; another situation is that this thing can only be delegated to other objects to do, the following example I will explain this situation.

The following code I want to implement a simple function, the scenario is described as follows: TableView There are more than one customtableviewcell,cell above is a text message and a detail button, click button to push to a new page. Why is this scenario used by proxy delegate? Because the button is above the custom Customtableviewcell, and the cell does not have the ability to implement push, because the code that is push to the new page is like this,

[Self.navigationcontroller Pushviewcontroller ...];

So this time Customtableviewcell will entrust its controller to do this thing.

According to my coding habits, I like to write the agreement of the entrusted application in the header file of the class that presented the request, now the scene is Customtableviewcell put forward the request, the following 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 defines a protocol customcelldelegate in CustomTableViewCell.h, which has a pushtonewpage method that needs to be implemented, and then writes a property modifier for assign, The property named delegate, the reason why the use of assign is because it involves memory management of things, later in the blog I will specifically explain the reasons.

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 judgment in the above code is best written, because this is to determine whether self.delegate is null, and whether the controller implementing the Customcelldelegate protocol also implements the Pushtonewpage method.

The next is the class commissioned by the application, here is the corresponding Customtableviewcell where the Viewcontroller, it first to implement the Customcelldelegate protocol, and then to implement the Pushtonewpage method, Another thing you should not forget is to set the Customtableviewcell object cell delegate equals self, in many cases may forget to write cell.delegate = self, resulting in a problem I do not know foggy. The following key codes are all in VIEWCONTROLLER.M,

The first is to obey the Cumtomcelldelegate agreement, which everyone must know, like many system protocols, such as Uialertviewdelegate, Uitextfielddelegate, Uitableviewdelegate, Like Uitableviewdatasource.

@interface Viewcontroller () <CustomCellDelegate>

@property (nonatomic, strong) Nsarray *textarray;

@end

Then the Pushtonewpage method is implemented in the Customcelldelegate protocol,

-(void) pushtonewpage

{

DETAILVIEWCONTROLLER*DETAILVC = [[Detailviewcontroller alloc] init];

[Self.navigationcontroller PUSHVIEWCONTROLLER:DETAILVC Animated:yes];

}

Another step is the most easily forgotten, is to set the Cumtomtableviewcell object cell delegate, the following code,

-(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;

}

by cell.delegate = self; make sure the CUSTOMTABLEVIEWCELL.M judgment statement if (self.delegate && ...) {} The Self.delegate is not empty, at this time the self.delegate is actually Viewcontroller,cell object delegated Viewcontroller implementation Pushtonewpage method. This simple scenario describes a situation where a proxy is used, that is, Customtableviewcell does not have the ability to implement Pushviewcontroller functions, so the delegate Viewcontroller is implemented.

The code can be downloaded on GitHub.

If there is any mistake, please correct me.

----------------------------------------------below is the contents of block----------------------------------------------------

Block is a C language feature, as some people say in the group, it is the C language function pointer, in the use of the most is the function callback or event delivery, such as sending data to the server, waiting for the server feedback is successful or failure, the block will come in handy, The implementation of this function can also use the agent, so that, I feel that block is a bit like proxy it?

Before I touched block, I used it as a function parameter, and I didn't feel very well at the time. Now in the project, many times block as a property, so more simple and direct, think, actually property is not the definition of the composite stored variables, and block as a function parameter is also defined variables, so as function parameters or as a property of the nature of no difference.

Take a look at the syntax of the block that others summed up, http://fuckingblocksyntax.com, this link is bright, fucking block syntax, fuck block syntax ah. There are several uses of block,

1. As a local variable (locally variable)

ReturnType (^blockname) (parametertypes) = ^returntype (Parameters) {...};

2, as @property

@property (nonatomic, copy) ReturnType (^blockname) (parametertypes);

3, as a method of the parameters (methods parameter)

-(void) Somemethodthattakesablock: (ReturnType (^) (parametertypes)) Blockname;

4, as a method parameter is called when

[Someobject Somemethodthattakesablock: ^returntype (Parameters) {...}];

5, use typedef to define block, can do more with less

typedef returntype (^typename) (parametertypes);
TypeName blockname = ^returntype (Parameters) {...};

Above I just copy paste a bit, next or implement click Customtableviewcell above button Implementation page Jump function, I have more than once analogy block like delegate, here I am also thinking inertia, The following content I will be the block for the agent, some of the words described or similar to delegate. First, the property of block is defined in the Customtableviewcell of the request for delegation,

@interface Customtableviewcell:uitableviewcell

@property (nonatomic, strong) UILabel *text1label;

@property (nonatomic, strong) UIButton *detailbtn;

The following definitions, please compare the crossing

The definition of/*delegate I did not delete, because everyone can analogy to look down */

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

/* This defines the buttonblock*/

@property (nonatomic, copy) void (^buttonblock) ();

@end

This is the reason why I use the copy attribute to decorate the Buttonblock property, and I'll make a special explanation in the future blog.

Next, in the Customtableviewcell, give it the detailbtn on the top of the fixed-point method,

[Self.detailbtn addtarget:self Action: @selector (btnclicked:) forcontrolevents:uicontroleventtouchupinside];

Then the details of the btnclicked method, I have not deleted the contents of delegate, is to give you a comparison of block and delegate function and grammar similarity,

-(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're going to say now.

if (Buttonblock) {

Buttonblock ();

}

}

The following is a critical place to set the buttonblock of its Customtableviewcell cell object in ViewController2, which is to assign a value to it, where I still keep cell.delegate = self;

-(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, here just to give you an analogy.

Cell.delegate = self;

Buttonblock an indispensable code

Cell. Buttonblock = ^{

[Self pushToNewPage2];

};

return cell;

}

The reason the cell. Buttonblock = ^{}; Assignment is because we are defining buttonblock, void (^buttonblock) (), which means 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];

}

You see this method is similar to the Pushtonewpage method in the Customcelldelegate protocol. And then in the back to the analogy, is not block is a lite version of the delegate, because delegate design mode to write protocol customcelldelegate, there are easy to omit cell.delegate = self; But it's a lot easier when the block is used.

The latest code I have updated to GitHub, very simple, questionable or questionable friends can download to see.

Another: I am also an iOS development rookie, for a lot of details to understand not enough depth, the above code using ARC coding, if I write any problem or have any flaws, but also asked the great God to correct me.

I hope that there are developers to communicate with each other, improve technology, my e-mail: [email protected]. There is a QQ Exchange group 188647173, interested in can be added to discuss the discussion, learning and learning, but also hope that the big God to the group to give us rookie guidance.

Block is simple, just like delegate's simplified version.

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.