Block is same as the c function.The basic idea of a block is to treat a small piece of code as if it were a value. The piece of code can then be passed as a parameter in messages or assigned to a variable.
With the help of block it's very easy to write code which is simple , easy to debug, readable and maintainable. So let's have a look at the syntax and see how it works:
With the help of block it's very easy to write code which is simple , easy to debug, readable and maintainable. So let's have a look at the syntax and see how it works:
^{NSLog(@"This is a block"); }
A block is the only object that begins its life in stack, rather than heap memory.A very effective use of a block literal is to deal with a callback.
Creating a block variable:
int (^sum)(int, int) = ^(int a , int b){
return a+b;
}
This is a simple block definition . It takes two parameters of type int and return one int parameter.
To call this block as:
int c = sum(3,5);
NSLog(@"sum is %d",c);
When a block is created, it will capture, or close around, the values of those variables that the code has referred to and that are in the same lexical scope of the block. Essentially, a snapshot is taken of these values. These values are preserved in the memory allocated for the block and cannot later be changed. It is said that these variables are "captured by value".
To change the this behavior(to use the latest values of the variable), we can declare these variable as
__block storage specifier.
__block int z =5;
Block as method parameter: We can also use block as method parameter to use call back. For example:
-(void)validateString:(NSString *)str onCompletion:(void(^)(bool isValidate))completion{
if(str.length ==0){
completion(NO); //call block
}else{
completion(YES);
}
}
Now call this method as
[self validateString:@"demoiOS" onCompletion:^(bool isValidate){
if(isValidate){
//str is valid, handle it
}else{
// str is not valid, handle it here
}
}];