Block is equivalent to the function pointer in C or C ++, and is equivalent to the delegate in. Net or Java.
// Block Declaration
Double (^ blockname) (double, double) =
^ Double (double firstparam, double secondparam ){
Return firstparam * secondparam;
}
// Block call
Double result = blockname (2, 4 );
Block will form a closure
-(Void) testmethod {
Int I = 42;
Void (^ testblock) (void) = ^ {
Nslog (@ "% I", I );
};
I = 84;
Testblock ();
}
In this Code, the value 42 of block I is testblock capture. Even if the I value is modified before testblock is called, the execution result of testblock is still 42. in addition, even if I is modified in testblock, the original I value will not be affected.
You can use the _ block keyword to share the variables defined outside the block with the code in the block.
_ Block int I = 42;
Void (^ testblock) (void) = ^ {
Nslog (@ "% I", I );
I = 100;
}
Testblock ();
Nslog (@ "% I", I );
In this case, the output result is 42,100.
Block is usually passed to the method as a parameter and serves as a callback function. Block parameters are generally placed at the end of the method parameter list.
-(Void) testmethod: (nsstring *) STR callback: (void (^) (void) testblock;
Use typedef to simplify block syntax
Typedef void (^ nothinblock) (void );
In this way, you can create nothinblock instances to create blocks with the same signature.
Nothinblock callback = ^ {
...
};
If you define a block type attribute in a class, and this block captures self, it may cause a strongly referenced loop.
@ Interface nothin: nsobject
@ Property (copy) void (^ block) (void );
@ End
@ Implementation nothin
-(Void) configureblock {
Self. Block = ^ {
[Self dosomething];
}
}
@ End
Because self is a strong reference to the block, and the block has capture self, this will cause a strong reference loop. To avoid this situation, we need to use weak references to self in the block.
-(Void) configureblock {
Nothin * _ weak weakself = self;
Self. Block = ^ {
[Weakself dosomething];
}
}
In this case, when the block is executed, the reference to self is removed.