I am messed with both completion handler and blocks while I am using them in Swift
and Objective-C
. And when I am searching blocks in Swift
on google it is showing result for completion handler! Can somebody tell me what is the difference between completion handler and blocks with respect to Swift
and Objective-C
?
Here you can easily differentiate between blocks and completion handlers in fact both are blocks see detail below.
Blocks:
Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary.
Syntax: ReturnType (^blockName)(Parameters) see example:
int anInteger = 42;
void (^testBlock)(void) = ^{
NSLog(@"Integer is: %i", anInteger); // anInteger outside variables
};
// calling blocks like
testBlock();
Block with argument:
double (^multiplyTwoValues)(double, double) =
^(double firstValue, double secondValue) {
return firstValue * secondValue;
};
// calling with parameter
double result = multiplyTwoValues(2,4);
NSLog(@"The result is %f", result);
Completion handler:
Whereas completion handler is a way (technique) for implementing callback functionality using blocks.
A completion handler is nothing more than a simple block declaration passed as a parameter to a method that needs to make a callback at a later time.
Note: completion handler should always be the last parameter in a method. A method can have as many arguments as you want, but always have the completion handler as the last argument in the parameters list.
Example:
- (void)beginTaskWithName:(NSString *)name completion:(void(^)(void))callback;
// calling
[self beginTaskWithName:@"MyTask" completion:^{
NSLog(@"Task completed ..");
}];
More example with UIKit
classes methods.
[self presentViewController:viewController animated:YES completion:^{
NSLog(@"xyz View Controller presented ..");
// Other code related to view controller presentation...
}];
[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..");
}];