Using Blocks as Method Parameters

Another method of using blocks is to use them as method parameters. A common use case for this is a completion handler for a long-running or asynchronous task. To use a block as a completion handler, first a method must be declared with a completion block as a parameter.

- (void)longRunningTaskWithCompletionHandler:   (void(^)(void))completionBlock{    ...    if (completionBlock) {        completionBlock();    }}

The syntax might look a bit awkward, but the method declares that it should receive a block with no parameters and no return type as a parameter. When the method has completed, it will execute the passed-in completion block. This allows the caller to avoid having to set ...

Get iOS Components and Frameworks: Understanding the Advanced Features of the iOS SDK now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.