Blocks are simply a way of creating callback code at the time of invocation. The structure is actually very similar to how typically I would create functions in Javascript. Take the following block example in Objective-C:
int (^Multiply)(int, int) = ^(int num1, int num2) { return num1 * num2; }; int result = Multiply(7, 4); // result is 28
Look familiar? That’s because the structure is similar to Javascript:
var Multiply = function (num1, num2) { return num1 * num2; }; var result = Multiply(7, 4); // result is 28
As a use case, I needed to execute code upon completion of an animation. Originally, I had the following code:
[self hideReportButtons] [UIView beginAnimations:@"animationId" context:nil]; [UIView setAnimationDuration:1.0]; [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:webReportView cache:YES]; webReportView.hidden = YES; [UIView commitAnimations];
Unfortunately with the above code, I didn’t have control of the timing of the execution of code. With blocks, I’m able to execute code specifically when the animation ends, which is exactly what I needed:
[UIView transitionWithView: webReportView duration: 1.5 options: UIViewAnimationOptionTransitionCurlUp animations: ^{ webReportView.hidden = YES; } completion: ^(BOOL finished) { [self hideReportButtons]; } ];
The end result is a cleaner and more easily understandable code.