The block function is a function pointer-like function, the programmer only need to put the code needs to be encapsulated in the definition of the block can be used in the future, the direct invocation, very convenient ....
Examples are as follows:
Customizing a block with no parameters
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool
{
//The first form: custom block function type without parameters
typedef void (^FirstBlock)(void);
//Create a block and encapsulate the code
FirstBlock block = ^(void){
for (int i=0; i<5; i++)
{
NSLog(@"i:%d",i);
}
};
//Call the block function
block();
return 0;
}
Operation Result:
2015-10-17 18:38:35.317 Custom Block function [2507:145127] i:0
2015-10-17 18:38:35.319 Custom Block function [2507:145127] i:1
2015-10-17 18:38:35.319 Custom Block function [2507:145127] i:2
2015-10-17 18:38:35.319 Custom Block function [2507:145127] i:3
2015-10-17 18:38:35.319 Custom Block function [2507:145127] i:4
Program ended with exit code: 0
Customizing a block with parameters
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool
{
//The second form: custom block function type with parameters
typedef void (^SecondBlock)(int);
//Create a block and encapsulate the code
SecondBlock block = ^(int length){
for (int i=0; i<length; i++)
{
NSLog(@"i:%d",i);
}
};
//Call the block function
block(5);
}
return 0;
}
Operation Result:
2015-10-17 18:38:35.317 Custom Block function [2507:145127] i:0
2015-10-17 18:38:35.319 Custom Block function [2507:145127] i:1
2015-10-17 18:38:35.319 Custom Block function [2507:145127] i:2
2015-10-17 18:38:35.319 Custom Block function [2507:145127] i:3
2015-10-17 18:38:35.319 Custom Block function [2507:145127] i:4
Program ended with exit code: 0
Objective-c: Custom Block function