Difference Between Completion Handler and Blocks : [iOS]
Asked Answered
N

4

28

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 ?

Nuncio answered 21/9, 2016 at 7:11 Comment(1)
All completion handlers are blocks, but not all blocks are completion handlers.Kroeger
D
36

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.

  • They can be executed in a later time, and not when the code of the scope they have been implemented is being executed.
  • Their usage leads eventually to a much cleaner and tidier code writing, as they can be used instead of delegate methods, written just in one place and not spread to many files.

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..");
                     }];
Drudge answered 21/9, 2016 at 8:28 Comment(0)
S
10

Blocks: Obj-c

- (void)hardProcessingWithString:(NSString *)input withCompletion:(void (^)(NSString *result))block;

[object hardProcessingWithString:@"commands" withCompletion:^(NSString *result){
    NSLog(result);
}];

Closures: Swift

func hardProcessingWithString(input: String, completion: (result: String) -> Void) {
    ...
    completion("we finished!")
}

The completion closure here for example is only a function that takes argument string and returns void.

Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

Closures are first-class objects, so that they can be nested and passed around (as do blocks in Objective-C). In Swift, functions are just a special case of closures.

Suzannasuzanne answered 21/9, 2016 at 7:22 Comment(0)
P
8

In short : Completion handlers are a way of implementing callback functionality using blocks or closures. Blocks and Closures are chunks of code that can be passed around to methods or functions as if they were values (in other words "anonymous functions" which we can give names to and pass around).

Pending answered 21/9, 2016 at 7:13 Comment(0)
L
3

I am hope this will help.

First Step:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController


-(void)InsertUser:(NSString*)userName InsertUserLastName:(NSString*)lastName  widthCompletion:(void(^)(NSString* result))callback;

@end

Second Step :

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

-(void)InsertUser:(NSString *)userName InsertUserLastName:(NSString*)lastName widthCompletion:(void (^)(NSString* result))callback{

    callback(@"User inserted successfully");

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self InsertUser:@"Ded" InsertUserLastName:@"Moroz" widthCompletion:^(NSString *result) {

        NSLog(@"Result:%@",result);

    }];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
Later answered 21/6, 2018 at 10:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.