codescracker


objective c

Objective-C Blocks



« Previous Tutorial Next Tutorial »


Blocks are a language-level featured added to Objective-C, that allows 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 the collections like NSArray or NSDictionary.

Here is the general form of the block in Objective-C:

return-type (^blockName)(argumentType);

Here is the Simple block implementation:

return-type (^blockName)(argumentType)= ^{
};

Objective-C Block Example

Here is an example, showing the block in Objective-C:

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

You can invoke block using

simpleBlock();

Objective-C blocks can also take arguments and return values like functions. Here is a simple example to implement and invoke a block along with their arguments 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);

Here is an example program using the typedef in block in Objective-C.

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

When the above code is compile and executed, it will produce the following result:

2014-06-03 13:18:37.932 demo[284:303] Action Performed
2014-06-03 13:18:37.932 demo[284:303] Here, Completion is called to intimate action is performed.

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test