Objective-C Blocks

Blocks Objective-C            
     
              An Objective-C class characterizes an item that consolidates information with related conduct. Once in a while, it bodes well just to speak to a solitary errand or unit of conduct, as opposed to a gathering of strategies.

             Pieces are a dialect level highlight added to C, Objective-C and C++ which permit you to make particular fragments of code that can be gone around to systems or capacities as though they were qualities. Pieces are Objective-C objects which implies they can be added to accumulations like NSArray or NSDictionary. They additionally can catch values from the encasing degree, making them like terminations or lambdas in other programming dialects

Simple Block declaration syntax

returntype (^blockName)(argumentType);
Straightforward square execution

returntype (^blockName)(argumentType)= ^{
};
Here is a straightforward illustration

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

We can summon the square utilizing

simpleBlock();
Blocks Take Arguments and Return Values
Squares can likewise take contentions and return values simply like techniques and capacities. 

Here is a basic sample to execute and conjure a piece with contentions 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 definitions

Here is a straightforward illustration utilizing typedef as a part of piece. It would be ideal if you take note of this example doesn't deal with the online compiler until further notice. Use XCode to run the same.

#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()
{
    /* my first program in Objective-C */
    SampleClass *sampleClass = [[SampleClass alloc]init];
    [sampleClass performActionWithCompletion:^{
        NSLog(@"Completion is called to intimate action is performed.");
    }];
    
    return 0;
}

Give us a chance to aggregate and execute it, it will deliver the accompanying result:

2013-09-10 08:13:57.155 demo[284:303] Action Performed
2013-09-10 08:13:57.157 demo[284:303] Completion is called to intimate action is performed.

Squares are utilized all the more as a part of iOS applications and Mac OS X. So its more essential to comprehend the utilization of squares.

0 comments:

Post a Comment

My Instagram