The first int is the return type. Then in parentheses comes the caret introducing the block variable calledtriple. Finally we have a list of parameter types in parentheses (oneint in this case). The block literal on the right-hand side of the assignment conforms to this type. Note, however, that as a matter of convenience there's no need to declare the return type of the block literal. The compiler can infer it from the return statement.
To call the block, you need to pass the number to be tripled and (ideally) do somethingwith the return value, like so:
[cpp]
int result = triple(2);
By way of comparison, here's how you would declare and create a block that takes twoint parameters, multiplies them together, and returns the result as anint value:
[cpp]
int (^multiply)(int,int) = ^(intx, int y) {
returnx * y;
};
And here's how you'd call this block:
[cpp]
int result = multiply(2, 3);
Declaring block variables gave us an opportunity to explore block types and how to call blocks. The block variable looks like a function pointer and calling the block is similar to calling a function. But unlike function pointers, blocks are actually Objective-C objects. And that means we can pass them around like other objects.
Methods Can Take Blocks
Now, in practice blocks are most useful when you pass them as parameters to methods that in turn call the block. And when you're passing a block to a method, it's usually more convenient to use inline blocks rather than assigning the block to a typed variable and then passing it to the method. For instance, we used inline blocks in the animation and enumeration examples we saw earlier.
Apple has added methods to their frameworks that take blocks, and you can write APIs that take blocks, too. For example, suppose we want to create aWorker class method that takes a block and repeatedly calls it a given number of times, passing in the repeat count each time. Here's how we might call that method with an inline block that triples each number (1 through 10):
[cpp]
[Worker repeat:10 withBlock:^(intnumber) {
returnnumber * 3;
}];
The method could handle any block that takes a single int parameter and returns anint result. Want to double all the numbers Just give the method a different block.
Your Turnwww.2cto.com
OK, so how would you implement the repeat:withBlock: method above to accept and call a passed block Give it some thought, and we'll tackle it in thenext installment. In the meantime, practice using blocks by calling theenumerateKeysAndObjectsUsingBlock: method with a block that prints the keys and values of thisNSDictionary:
[cpp]
NSDictionary*cards =
[NSDictionarydictionaryWithObjectsAndKeys:@"Queen", @"card",
@"Hearts", @"suit",
@"10", @"value",nil];
Have fun, and stay tuned for more on blocks...
作者:likendsl