We’ve seen examples of invoking block objects in Constructing Block Objects and Their Syntax and Variables and Their Scope in Block Objects. This section contains more concrete examples.
If you have an independent block object, you can simply invoke it just like you would invoke a C function:
void (^simpleBlock)(NSString *) = ^(NSString *paramString){ /* Implement the block object here and use the paramString parameter */ }; - (void) callSimpleBlock{ simpleBlock(@"O'Reilly"); }
If you want to invoke an independent block object within another independent block object, follow the same instructions by invoking the new block object just as you would invoke a C method:
/*************** Definition of first block object ***************/ NSString *(^trimString)(NSString *) = ^(NSString *inputString){ NSString *result = [inputString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; return result; }; /*************** End definition of first block object ***************/ /*************** Definition of second block object ***************/ NSString *(^trimWithOtherBlock)(NSString *) = ^(NSString *inputString){ return trimString(inputString); }; /*************** End definition of second block object ***************/ - (void) callTrimBlock{ NSString *trimmedString = trimWithOtherBlock(@" O'Reilly "); NSLog(@"Trimmed string = %@", trimmedString); }
In this example, go ahead and invoke the callTrimBlock
Objective-C method:
[self callTrimBlock];
The callTrimBlock
method will
call the trimWithOtherBlock
block
object, and the trimWithOtherBlock
block object will call the trimString
block object in order to trim the given string. Trimming a string is an
easy thing to do and can be done in one line of code, but this example
code shows how you can call block objects within block objects.
In Chapter 2, you will learn how to invoke block objects using Grand Central Dispatch, synchronously or asynchronously, to unleash the real power of block objects.