+2 votes
in C Plus Plus by
What are blocks and how are they used in Objective-C?

1 Answer

0 votes
by

Blocks are a way of defining a single task or unit of behavior without having to write an entire Objective-C class. Under the covers Blocks are still Objective C objects. They are a language level feature that allow programming techniques like lambdas and closures to be supported in Objective-C. Creating a block is done using the ^ { } syntax:

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

It can be invoked like so:

myBlock();

It is essentially a function pointer which also has a signature that can be used to enforce type safety at compile and runtime. For example you can pass a block with a specific signature to a method like so:

- (void)callMyBlock:(void (^)(void))callbackBlock;

If you wanted the block to be given some data you can change the signature to include them:

- (void)callMyBlock:(void (^)(double, double))block {
    ...
    block(3.0, 2.0);
}

Related questions

0 votes
asked Nov 12, 2020 in C Plus Plus by Hodge
+1 vote
asked Jan 17, 2022 in FuelPHP by DavidAnderson
...