iOS Learning (OC language) Knowledge Point finishing
First, the introduction of Block
1) Concept: block is a data type, similar to the C language without the name of a function, you can receive parameters, you can also return the value of the same as the C function is called
Encapsulates a piece of code that can be called from anywhere or as a function parameter, as well as a function return value
2) Block Instance code
1 //A variable that defines a block type Myblock,myblock type can only point to a parameter with two int and a code block that returns an int2typedefint(^myblock) (int,int); 3 //define a function pointer4 int(*pmath) (int,int); 5 6 intAddintAintb)7 { 8 returnA +b;9 }Ten One intSubintAintb) A { - returnA-b; - } the - intMainintargcConst Char*argv[]) { - @autoreleasepool { -Pmath = add;//pointing to the function pointer + //NSLog (@ "sum:%d", pmath (2,3)); -Pmath =Sub; + A //defines a block,block that can only point to a parameter with 2 int, which returns the code block of int at //starting with ^ as a code block, followed () is a parameter, and then {} code block - int(^BLOKE1) (int,int) = ^(intAintb) { - returnA +b; - }; - - ints = Bloke1 (3,5); inNSLog (@"s:%d", s); - //defines a block that points to blocks of code that have no parameters and no return value (no arguments, void can be omitted) to void(^BLOCK2) (void) = ^{ +NSLog (@"programing is fun!"); - }; the Block2 (); * int(^BLOCK3) (int,int) = ^(intAintb) { $ returnA-b;Panax Notoginseng - }; the + //defines a variable of type Myblock, an assignment code block AMyblock Block4 = ^ (intAintb) { the returnA *b; + }; - $NSLog (@"%d", Block4 (2,5)); $ - intc =Ten; -__blockintD =1; the //Block blocks can access variables outside of blocks but cannot be modified, and if needed, the variable is preceded by a __block modifier - void(^BLOCK5) (void) = ^{ WuyiD = d+2; theNSLog (@"c:%d,d:%d", c,d); - }; Wu block5 (); - } About return 0; $}
IOS Stage Learning 24th Day Notes (introduction of block)