(1) define methods and calls for pointers to functions:
#import <Foundation/Foundation.h>void test(){ NSLog(@"hello");}int main(int argc, const char * argv[]) { @autoreleasepool { //定义 void (*p1)()=test; //使用 p1(); } return 0;}
The definition of block is similar to that of block.
//定义block,注意^以及末尾的分号;右边的函数体也不再需要函数名称,只要前面有myBlock即可 void (^myBlock)()=^{ NSLog(@"hello"); }; //调用,和函数类似 myBlock();
The difference between block and pointer to a function is that the latter can only put a function name behind it, rather than directly putting the code (function body) of the function behind it. The former makes up for this defect, which is equivalent to "encapsulating" the entire code block.
(2) block with Parameters
//定义block,注意^以及末尾的分号; int (^sum1)(int a,int b)=^int (int a,int b){ return a+b; }; //调用,和函数类似 NSLog(@"%d",sum1(5,6));
(3) Since it is a data type, it can also be passed as a parameter.
(4) If you need to change the variable outside the block in the block code, add the _ block keyword before the variable.
[OC enhancement] defines and calls block data types, and transmits parameters to other applications.