// ------- 1. Define the function ----- // 1. Function int sum (int A, int B) {return a + B ;} // ------------------ 2. Declare --------- // 2. Declare the function pointer [Replace sum with * P.] int (* p) (int A, int B ); // (1) Declare block [Replace sum with ^ myblock] int (^ myblock) (int A, int B); // define void (^ myblock2) (void);-(void) viewdidload {[Super viewdidload]; // --------------------- 3. assign a value [difference] ------------------ // 3. assign a value to the function pointer P = sum; // (2) Assign the function value to myblock [^ Add the parameter list and the content of the code block after it, and end with ";"] myblock = ^ (int A, int B) {return a + B ;}; // --------------------- 4. Call ------------------ // 4. Call int result = P (3, 6); nslog (@ "% d", result ); // (3) Call int resultblock = myblock (3, 6); nslog (@ "% d", resultblock); myblock2 = ^ (void) {nslog (@ "myblock2 executed") ;}; myblock2 (); // --------------------- 2. File Transfer Value -------------------- // block call person * person = [[person alloc] init]; // 1-2 implement block // ^ int (int, int B) {// return a + B; // It is a constant to upload the 10 and 20 of person to the block of this file. // It is a local variable, to change the value, add _ block int number = 10 before the declaration; int resultps = [person testmethod: ^ int (int A, int B) {number = 20; Return A + B + number;}]; // create int resultps2 = [person testmethod2: ^ int (int A, int B) in typedef Mode) {return a + B;}]; nslog (@ "resultps: % d resultps2: % d", resultps, resultps2);} @ end
Person. h
# Import <Foundation/Foundation. h> // here, the personblock is the type name, which can be understood as inttypedef int (^ personblock) (int A, int B); @ interface person: nsobject // declare the block in the parameter [int (^) (int A, int B]-(INT) testmethod :( int (^) (int A, int B; // you do not need to add the star number-(INT) testmethod2 :( personblock) block; @ end
Person. m
# Import "person. H "@ implementation person // call block-(INT) testmethod :( int (^) (int A, int B) block {return block );} -(INT) testmethod2 :( personblock) block {return block (1, 2) ;}@ end
Block Series 1: first recognized Block