Objective C Tutorial - Objective C Blocks






Blocks in Objective-C are similar to closures or lambdas in other programming languages

Syntax

Here is the syntax to declare a block in Objective-C.

returntype (^blockName)(argumentType);

The following is the syntax we can use to implement the block.

returntype (^blockName)(argumentType)= ^{
};

Example

The following code defines a block.

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

We can invoke the block using.

simpleBlock();




Example 2

Here is a simple example using typedef in block.

#import <Foundation/Foundation.h>

typedef void (^CompletionBlock)();

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

@implementation SampleClass

- (void)performActionWithCompletion:(CompletionBlock)completionBlock{

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

@end

int main()
{
    SampleClass *sampleClass = [[SampleClass alloc]init];
    [sampleClass performActionWithCompletion:^{
        NSLog(@"output.");
    }];
    
    return 0;
}