Block in Objective C

Blocks are Objective-C objects which means they can be added to collections like NSArray or NSDictionary. They also have the ability to capture values from the enclosing scope, making them similar to closures or lambdas in other programming languages

Simple Block declaration syntax

returntype (^blockName)(argumentType);

Simple block implementation

returntype (^blockName)(argumentType)= ^{
};
void (^simpleBlock)(void) = ^{
   NSLog(@"This is a block");
};
simpleBlock();

Blocks Take Arguments and Return Values

double (^multiplyTwoValues)(double, double) = 
   ^(double firstValue, double secondValue) {
      return firstValue * secondValue;
   };

double result = multiplyTwoValues(2,4); 
NSLog(@"The result is %f", result);

Blocks Using Type Definitions

#import <Foundation/Foundation.h>

typedef void (^CompletionBlock)();
@interface SampleClass:NSObject
- (void)performActionWithCompletion:(CompletionBlock)completionBlock;
@end

@implementation SampleClass

- (void)performActionWithCompletion:(CompletionBlock)completionBlock {

   NSLog(@"Action called");
   completionBlock();
}

@end

int main() {
   
   /* my first program in Objective-C */
   SampleClass *sampleClass = [[SampleClass alloc]init];
   [sampleClass performActionWithCompletion:^{
      NSLog(@"intimate action is performed.");
   }];

   return 0;
}

Let us display result −

Action called
intimate action is performed.