Header Ads

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

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

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


Blocks using type definition

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 *obj1 = [[SampleClass alloc]init];
       [obj1 performActionWithCompletion :^{
               NSLog(@"Completion is called to intimate action is performed. ");
     }];
      return 0;
}


Blocks are used more in IOS application and Mac OS X. So its more important to understand the usage of blocks.

No comments:

Powered by Blogger.