今天讲Objective-C中带参数和返回值的Block。
下面是ios reference官方的讲解:
Blocks Take Arguments and Return Values
Blocks can also take arguments and return values just like methods and functions.
As an example, consider a variable to refer to a block that returns the result of multiplying two values:
double (^multiplyTwoValues)(double, double);
The corresponding block literal might look like this:
^ (double firstValue, double secondValue) {
return firstValue * secondValue;
}
The firstValue and secondValue are used to refer to the values supplied when the block is invoked, just like any function definition. In this example, the return type is inferred from the return statement inside the block.
If you prefer, you can make the return type explicit by specifying it between the caret and the argument list:
^ double (double firstValue, double secondValue) {
return firstValue * secondValue;
}
Once you’ve declared and defined the block, you can invoke it just like you would a function:
double (^multiplyTwoValues)(double, double) =
^(double firstValue, double secondValue) {
return firstValue * secondValue;
};
double result = multiplyTwoValues(2,4);
NSLog(@"The result is %f", result);