Objective-C basic notes (6) Block
Block encapsulates a piece of code that can be executed at any time.
Block can be used as a function parameter or function return value, and it can also contain an input parameter or return value. It is similar to the traditional function pointer, but there is a difference: the block is inline (inline function), and by default it is read-only for local variables.
Apple's official recommendation is to use block as much as possible. It is widely used in multithreading, asynchronous tasks, set traversal, set sorting, and animation transfer.
Block definition:
Int (^ MySum) (int, int) = ^ (int a, int B ){
Return a + B;
}
Defines a block object called MySum. It has two int parameters and returns the int type. The right side of the equal sign is the specific implementation of the block.
Void test () {// defines a block. The return value of this block is of the int type. It receives two int type parameters, int (^ Sum) (int, int) = ^ (int, int B) {return a + B ;}; int a = Sum (10, 11); NSLog (@ "% I", );}
Void test2 () {// block can access local variables, but int c = 15 cannot be modified by default; // use the _ block keyword, the variable can be changed to _ block int B = 25; MySum sum = ^ (int a, int B) {NSLog (@ "C is % I", c ); B = 35; NSLog (@ "B is % I", B); return a + B ;}; NSLog (@ "% I", sum (10, 10 ));}
In the previous article, we implemented a button listener. In this article, we used block to implement the button listener.
# Import
@ Class Button; typedef void (^ ButtonBlock) (Button *); @ interface Button: NSObject // currently use assign @ property (nonatomic, assign) ButtonBlock; // click the analog button-(void) click; @ end
In Button. h, we define a data type void (^ ButtonBlock) (Button *), and then define a member variable ButtonBlock of this type;
Added a member method-(void) click;
#import "Button.h"@implementation Button- (void)click { _block(self);}@end
The-(void) click method is implemented in the Button. m file.
Int main (int argc, const char * argv []) {@ autoreleasepool {Button * btn = [[[Button alloc] init] autorelease]; btn. block = ^ (Button * btn) {NSLog (@ "Button % @ clicked", btn) ;}; // click the simulation Button [btn click];} return 0 ;}
Finally, in the main function, we first get the button object, then assign values to the block object in the button object, and finally trigger the event when the simulated button is clicked.
Careful friends may find that the block defined here and the pointer to the function in the C language are particularly like, the two comparisons are as follows:
Int sum1 (int a, int B) {return a + B;} void test3 () {// Block int (^ sum) (int, int) = ^ (int, int B) {return a + B ;}; // pointer to the function int (* sum1) (int, int) = sum1; // call sum (11, 11 ); sum1 (10, 10 );}
typedef int(^MySum) (int, int);typedef int (*sum2)(int, int);