Featured post

Difference between protocol and delegates?

A protocol, declared with the ( @protocol syntax in Objective-C) is used to declare a set of methods that a class "adopts" (de...

Friday, 10 April 2015

What is Blocks in Objective-C ?

In Objective-C class defines an object that combines data with related     behaviour. Sometimes, it makes sense just to represent a single task or   unit of behaviour, rather than a collection of methods.

Blocks are a 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             closures or lambdas in other programming languages

Block declaration syntax:

returntype (^blockName)(argumentType);
Simple block implementation
returntype (^blockName)(argumentType)= ^{
};

Here is a simple example:


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

How to invoke:

simpleBlock();
 

No comments:

Post a Comment