Block - Objecive C
An Objective C defines an object that combines data with related behavior. Sometimes, it makes sense just to represent a single task or unit of behavior, rather than a collection of methods.
Blocks are language-level feature added to C, objective C and C++ which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. 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 closure or lambdas in other programming language.
Similar Block declaration syntax
Simple block implementation
HERE is simple example
Blocks Take Argument and Return Values
Blocks can also take argument and return values just like methods and functions.
Here is simple example to implementation and invoke a block with argument and return values.
Blocks using type definition
Here is a simple example using typedef in block.
Blocks are used more in IOS application and Mac OS X. So its more important to understand the usage of blocks.
Blocks are language-level feature added to C, objective C and C++ which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. 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 closure or lambdas in other programming language.
Similar Block declaration syntax
returntype (^blockName)(argumentType);
Simple block implementation
returntype (^blockName)(argumentType) = ^{
};
};
HERE is simple example
void (^simpleBlock)(void) = ^{
NSLog(@"this is a block");
};
We can invoke the block using
simpleBlock();
NSLog(@"this is a block");
};
We can invoke the block using
simpleBlock();
Blocks Take Argument and Return Values
Blocks can also take argument and return values just like methods and functions.
Here is simple example to implementation and invoke a block with argument 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);
^(double firstValue, double secondValue)
{
return firstValue * secondValue;
};
double result = multiplyTwoValues(2,4);
NSLog(@"The result is %f", result);
Blocks using type definition
Here is a simple example using typedef in block.
Blocks are used more in IOS application and Mac OS X. So its more important to understand the usage of blocks.
No comments: