Here you can easily distinguish between blocks and completion handlers. In fact, both blocks see below.
Blocks:
Blocks are a language-level function added to C, Objective-C, and C ++ that allow you to create separate code segments that can be passed to methods or functions as if they were values. Blocks are Objective-C objects, which means that they can be added to collections, such as NSArray or NSDictionary.
- They can be executed later, and not when the code that was implemented is executed.
- Their use ultimately leads to much cleaner and more accurate codes, since they can be used instead of delegation methods written simply in one place and do not apply to many files.
Syntax: ReturnType (^ blockName) (parameters) see example:
int anInteger = 42; void (^testBlock)(void) = ^{ NSLog(@"Integer is: %i", anInteger);
Block with argument:
double (^multiplyTwoValues)(double, double) = ^(double firstValue, double secondValue) { return firstValue * secondValue; };
Completion handler:
While a completion handler is a way (method) to implement a callback function using blocks.
A completion handler is nothing more than a simple block declaration passed as a parameter to a method that should call back later.
Note. The completion handler should always be the last parameter in the method. A method can have as many arguments as you want, but it should always have a completion handler as the last argument in the parameter list.
Example:
- (void)beginTaskWithName:(NSString *)name completion:(void(^)(void))callback;
An example using UIKit class UIKit .
[self presentViewController:viewController animated:YES completion:^{ NSLog(@"xyz View Controller presented ..");
[UIView animateWithDuration:0.5 animations:^{ // Animation-related code here... [self.view setAlpha:0.5]; } completion:^(BOOL finished) { // Any completion handler related code here... NSLog(@"Animation over.."); }];
vaibhav
source share