Objective C Blocks by Example
Objective C Blocks are self contained structures that reduces the complexity of delegations. The asynchronous calls that return results in background can use blocks. Blocks make sure both the calling and result handling to be placed in the same place. A simple block without return value and parameters is shown below.
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { // Block declaration void (^block)(void); // Block definition block = ^void(void){ NSLog(@"Perform task"); }; // Calling block block(); } return 0; }
Block in function
A function using a block is shown below.
@interface EezySample //Sample block declaration - (void)sampleBlock:(void (^)(void))block; @end @implementation EezySample //Sample block definition - (void)sampleBlock:(void (^)(void))block{ // Perform necessary tasks block();// notifying that process completed } @end int main(int argc, const char * argv[]) { @autoreleasepool { EezySample *eezySample= [[EezySample alloc] init]; // Calling a block [eezySample sampleBlock:^{ NSLog(@"Completed"); }]; } return 0; }