Block instead of callback

Source: Internet
Author: User

In addition to being able to define parameter lists, return types, blocks can also obtain state (such as local variables) within the lexical scope that is defined, and can modify these states under certain conditions, such as using the __block variable. In addition, these modifiable states are shared among multiple blocks within the same lexical scope, and can continue to share or modify these states, even if the lexical scope (such as stack expansion, out of scope) is out.

In general, blocks are encapsulated in short snippets of code that are used as work units, often for concurrent tasks, traversal, and callbacks.

For example, we can do something when we traverse the Nsarray:

[CPP] view plain copy-(void) Enumerateobjectsusingblock: (void (^) (id obj, Nsuinteger idx, BOOL *stop)) block;

If stop is set to Yes, it jumps out of the loop and does not continue to traverse.

In many frameworks, block is increasingly used as a callback function instead of the traditional callback method. Using block as a callback function allows programmers to write code more smoothly, without running halfway to another place to write a callback function, and sometimes to consider where the callback function is appropriate. With block, you can write the subsequent processing code directly when the function is called, passing it as a parameter for the callback at the end of its task execution. Another benefit is that block is used as a callback to directly access local variables. For example, I want to modify the name of a user in a batch of users, and then update the corresponding user's cell UI with a callback after the modification is complete. At this time I need to know the corresponding user cell index, if the use of traditional callback, you need to bring the index to the past, callback and return it back; the index of the current action cell is recorded by an external scope (this limits the name of only one user at a time) ; traverse to find the corresponding user. With block, you can access the cell's index directly.

This document mentions several applications of block: Callback processing message listener callback processing error callback handling enumeration callback view animation, transform sort

IOS4 has been directly supporting the blocks, it is necessary to learn a bit.

In iOS, blocks is treated as an object, which encapsulates a piece of code that can be executed at any time. Blocks can be used as a function parameter or as a return value of a function, and it can have an input parameter or return value itself. It is similar to a traditional function pointer, but differs: blocks is inline, and it is read-only to local variables.

Definition of blocks:

[CPP] view plain copy int (^myblock) (int a,int b) = ^ (int a,int b) {return a+b; };

Defines a blocks object named Myblock, which has two int parameters and returns an int. The right side of the equation is the concrete implementation of blocks, not a bit like the definition of a method.

Blocks can access local variables, but cannot be modified. For example, the following code will report a compilation error
[CPP] view plain copy int num = 0;           Use block int (^myblock) (int a,int b) = ^ (int a,int b) {num = a+b;       return num; };

If you want to change the keyword: __block (note that is two underscore "_")

[CPP] view plain copy __block int num = 0;           Use block int (^myblock) (int a,int b) = ^ (int a,int b) {num = a+b;       return num; };

As a function parameter, blocks replaces the callback function or delegate in some sense. When a function is called, it is assumed that an event is triggered, and then the contents of the blocks run. This facilitates the integration of code and reading, you do not need to go everywhere to implement the delegation method.

There are already a lot of support blocks parameters in the system API.

· Completion handlers

· Notification handlers

· Error handlers

· Enumeration

· View Animation and Transitions

· Sorting

For example:

[UIView animatewithduration: (nstimeinterval) duration animations: (void (^) ()) animations]

Blocks can also be used in aggregates. When enumerating an array we usually:

for (the ID obj in Array);

Right now

NSString *area = @ "Europe";

Nsarray *timezonenames = [Nstimezone knowntimezonenames];

Nsmutablearray *areaarray = [Nsmutablearray arraywithcapacity:1];

Nsindexset *areaindexes = [Timezonenames indexesofobjectswithoptions:nsenumerationconcurrent

passingtest:^ (id obj, Nsuinteger idx, BOOL *stop) {

NSString *tmpstr = (NSString *) obj;

return [Tmpstr Hasprefix:area];

}];

Nsarray *tmparray = [Timezonenames objectsatindexes:areaindexes];

[Tmparray enumerateobjectswithoptions:nsenumerationconcurrent| Nsenumerationreverse

usingblock:^ (id obj, Nsuinteger idx, BOOL *stop) {

[Areaarray addobject:[obj Substringfromindex:[area length]+1];

}];

    nslog (@ "Cities in%@ time zone:%@", area, Areaarray)

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.