Blocks in iPhone?

As a programmer, you’re used to data types like String, which is a variable type for text. We also are aware of things like int, float, and double, which are variable types to store numeric values. Finally, we know about things like NSObject, which is a foundation level class that allows us to bundle various collections of both data types and methods (a.k.a. functions). Blocks bring something significantly different to the table, providing a data type for executable code storage.
If that doesn’t make sense to you, don’t worry: blocks can be tough. Their purpose and function becomes much more clear upon seeing examples of their use. One of the most popular types of patterns in which blocks are used is for providing “completion blocks” to objects who perform some kind of asynchronous operation. The following is an example of a method signature provided in my UIView that takes advantage of accepting a completion block from a user:
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion;
That final completion parameter there is a block. As with all Objective-C methods, the method has named parameters. The animations and completion parameter are the blocks. You can tell because of the ^ character. This character is used to define a block. While a block variable type holds executable code, the block type itself must be defined. Just like when writing code within a method, blocks can provide objects to the code which it holds. Here we see the animation block defined first:
animations:(void (^)(void))animations
We can see this block returns void and provides void. In this block you would change all the UIKit animatable properties you would want. The completion block is a bit different though.
completion:(void (^)(BOOL finished))completion
In this block we can still see that we will be returning void. However, this time our block will be returning the completion BOOL for us to utilize if we like. When actually implementing this method in Xcode, the IDE does a lot of the work to get you past the somewhat jarring syntax of blocks. Once tabbed over to the parameter input for a block when calling a method, in Xcode 4 and above, hit enter and Xcode will create the outline of the block for you.
Perviously, you might imagine providing this functionality through the delegate pattern, but blocks are here now to allow for greater flexibility and will only become more popular with future versions of the SDK.
Reactions: