1.

What Are Blocks And How Are They Used?

Answer»

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);

}

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);

}



Discussion

No Comment Found