Introduction to Block in iOS (1) Basics and introduction to iosblock
Introduction to Block in iOS (I) Basics I. Overview
Block is a C-level syntax and runtime feature. Block is similar to a C function, but the flexibility of Block is reflected in the reference of stack memory and heap memory. We can even pass a Block as a parameter to other functions or blocks.
Ii. Warm-up
Let's first look at a simple Block example:
- Int multiplier = 7;
- Int (^ myBlock) (int) = ^ (int num ){
- Return num * multiplier;
- };
In this example, myBlock is a Block variable that accepts an int type parameter and returns an int type value. Is it like a C function?
Come on, let's take a look at typedef.
- Typedef void (^ BoolBlock) (BOOL); // a block that only accepts one BOOL parameter and does not return a value
- Typedef int (^ IntBlock) (void); // a block with no parameters returned
- Typedef BoolBlock (^ HugeBlock) (IntBlock); // check whether the parameters and returned values of this HugeBlock are blocks.
Iii. More detailed examples
Note: The above typedef is still valid ~
Take the initiative to call:
- -(Void) someMethod
- {
- BoolBlock ablock = ^ (BOOL bValue ){
- NSLog (@ "Bool block! ");
- };
- Ablock ();
- }
Return as a parameter:
- Typedef void (^ BoolBlock) (BOOL );
- -(BoolBlock) foo ()
- {
- BoolBlock ablock = ^ (BOOL bValue ){
- NSLog (@ "Bool block! ");
- };
- Return [[ablock copy] autorelease]; // copy it to the stack. For more details, see the subsequent sections.
- }
A member of the class:
- @ Interface OBJ1: NSObject
- @ Property (nonatomic, copy) BoolBlock block; // The reason is the same as above. Students
- @ End
-
- OBJ1 * obj1 =...
- Obj1.block = ^ (BOOL bValue ){
- NSLog (@ "Bool block! ");
- };
Parameters of other functions:
- -(Void) foo (BoolBlock block)
- {
- If (block ){
- Block ();
- }
- }
Other block parameters:
- BoolBlock bBlock = ^ (BOOL bV) {if (Bv) {/* do some thing */}};
- HugeBlock hBlock = ^ (BoolBlock bB) {bB ();};
-
- HBolck (bBlock );
Ah, global variables! :
- Static int (^ maxIntBlock) (int, int) = ^ (int a, int B) {return a> B? A: B ;};
- Int main ()
- {
- Printf ("% d \ n", maxIntBlock (2, 10 ));
- Return 0;
- }
Okay, you know how to use the block.
4. Special Mark __block
If you want to modify the stack variable declared outside the block, add _ block to the variable:
- Int main ()
- {
- _ Block int I = 1024;
- BoolBlock bBlock = ^ (BOOL bV ){
- If (bV ){
- I ++; // if there is no _ block mark, it cannot be compiled.
- }
- };
- }