今天开始新的一章,讲Block,C、C++、Objective-C都支持Block,就类似closures和lambdas。什么是Block,Block怎么用,今天开始讲。
下面是ios reference官方的讲解:
Working with Blocks
An Objective-C class defines an object that combines data with related behavior. Sometimes, it makes sense just to represent a single task or unit of behavior, rather than a collection of methods.
Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary. They also have the ability to capture values from the enclosing scope, making them similar to closures or lambdas in other programming languages.
This chapter explains the syntax to declare and refer to blocks, and shows how to use blocks to simplify common tasks such as collection enumeration. For further information, see Blocks Programming Topics.
Block Syntax
The syntax to define a block literal uses the caret symbol (^), like this:
^{
NSLog(@"This is a block");
}
As with function and method definitions, the braces indicate the start and end of the block. In this example, the block doesn’t return any value, and doesn’t take any arguments.
In the same way that you can use a function pointer to refer to a C function, you can declare a variable to keep track of a block, like this:
void (^simpleBlock)(void);
If you’re not used to dealing with C function pointers, the syntax may seem a little unusual. This example declares a variable called simpleBlock to refer to a block that takes no arguments and doesn’t return a value, which means the variable can be assigned the block literal shown above, like this:
simpleBlock = ^{
NSLog(@"This is a block");
};
This is just like any other variable assignment, so the statement must be terminated by a semi-colon after the closing brace. You can also combine the variable declaration and assignment:
void (^simpleBlock)(void) = ^{
NSLog(@"This is a block");
};
Once you’ve declared and assigned a block variable, you can use it to invoke the block:
simpleBlock();