Objective-C Block Syntax

How to declare blocks in Objective-C.

To define an object that combines data with related behavior, an Objective-C class is used. In some cases, it is more appropriate to represent a single task or behavior unit, rather than a group of methods.

Blocks are a language-level feature that has been added to C, Objective-C, and C++. They allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are considered Objective-C objects, which means they can be included in collections like NSArray or NSDictionary. Additionally, they can capture values from the enclosing scope, making them similar to closures or lambdas in other programming languages.

Local variable:

returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};

Property:

@property (nonatomic, copy, nullability) returnType (^blockName)(parameterTypes);

Method parameter:

- (void)methodWithBlock:(returnType (^nullability)(parameterTypes))blockName;

Pass as argument:

[someObject methodWithBlock:^returnType (parameters) {...}];

Typedef:

typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters) {...};