I. Overview
Block is a C-level syntax and runtime feature. Block is similar to the C function, but the block is more flexible than the C function, which is reflected in the stack memory, heap memory reference, and we can even pass a block as a parameter to other functions or block.
Second, warm up
Let's look at a relatively simple block example:
- int multiplier = 7;
- Int (^myblock) (int) = ^ (int num) {
- return num * multiplier;
- };
In this example, Myblock is a block variable that takes a parameter of type int and returns a value of type int. Does it look like a C function?
Come on, let's have a typedef.
- typedef VOID (^boolblock) (BOOL); A block that accepts only one bool parameter and no return value
- typedef INT (^intblock) (void); A block with no parameters that returns an int
- typedef boolblock (^hugeblock) (Intblock); //See, this hugeblock parameter and return value are block
Third, more detailed examples
Note: The typedef above are also valid ~
Take the initiative to call:
- -(void) SomeMethod
- {
- Boolblock Ablock = ^ (BOOL bValue) {
- NSLog (@"Bool block!");
- };
- Ablock ();
- }
Returned as a parameter:
- typedef VOID (^boolblock) (BOOL);
- -(Boolblock) foo ()
- {
- Boolblock Ablock = ^ (BOOL bValue) {
- NSLog (@"Bool block!");
- };
- return [[ablock copy] autorelease]; //must copy, copy it to the heap, more detailed principles, will be explained in the following chapters
- }
A member of the class:
- @interface Obj1:nsobject
- @property (nonatomic, copy) Boolblock block; //Reason ditto, students
- @end
- OBJ1 *obj1 = ...
- Obj1.block = ^ (BOOL bValue) {
- NSLog (@"Bool block!");
- };
Parameters for other functions:
- -(void) foo (Boolblock block)
- {
- if (block) {
- Block ();
- }
- }
Even 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;
- }
Well, you know how the block might be used.
Four, special markings, __block
If you want to modify the stack variables declared outside of block within a block, be sure to add __block tags to the variable:
- int main ()
- {
- __block int i = 1024x768;
- Boolblock bblock = ^ (BOOL BV) {
- if (BV) {
- i++; //If there is no __block tag, it cannot be compiled.
- }
- };
- }
Article Source: http://www.cnblogs.com/shouce/p/5522180.html
Introduction to block in iOS