IOS block--in Lan Yi education

Source: Internet
Author: User

1:int multiplier = 7;
   2:int (^myblock) (int) = ^ (int num)
   3: {
   4:     return num * multiplier;
   5:};

We use it to explain this example (please translate the words in the text box as follows):

We declare a "myblock" variable and use the "^" symbol to indicate that it is a block.

This is the complete definition of block, which will be assigned to the "myblock" variable.

Indicates that "myblock" is a block with a callback value of integer (int).

It has a parameter, and the pattern is also an integer.

The name of this parameter is called "num".

This is the contents of the block.

It is important to note that blocks can use the same variables that define the scope themselves, and you can imagine that in the example above, multiplier and myblock are all two variables defined within a function, and this variable is in the middle of a function two braces "{" and "}". Because their effective range is the same, the multiplier variable can be used directly in the block, and when the block is defined as a variable, we can use it directly as a general function:

   1:int multiplier = 7;
   2:int (^myblock) (int) = ^ (int num)
   3: {
   4:     return num * multiplier;
   5:};
   6:printf ("%d", Myblock (3));
   7://Results will print out 21

x.1.2 Direct use of block

In many cases, we do not need to declare the block as a variable, whereas we can directly write the block's contents directly in the place where we need to use block, in the following example Qsort_b function, which is a similar traditional qsort_t function, But use block directly as its parameter:

   1:char *mycharacters[3] = {"Tomjohn", "George", "Charles Condomine"};
   2:qsort_b (Mycharacters, 3,
   3:          sizeof (char *),
   4:          ^ (const void *l, const void *r)//block part
   5:             {
   6:                 Char *left = * (char * *) L;
   7:                 Char *right = * (char * *) R;
   8:                 return strncmp (left, right, 1);
   9:             }                            //end
  10:);

x.1.3 __block Variable

In general, only variables in the same scope can be read within the block and there is no way to modify any variables defined outside the block, and if we want these variables to be modified in the block, we must hang the __block modifier in front of it, in the first example above Multiplier, this variable in the block is read-only, so multiplier = 7 after the specified, in the block multiplier can only be 7 can not be modified, if we modify the multiplier in the block, the editor will Generates an error, so if you want to modify multiplier in a block, you must precede the multiplier with the __block modifier, see the following example:

   1: __block int multiplier = 7;
   2:int (^myblock) (int) = ^ (int num)
   3:                         {
   4:                             if (num > 5)
   5:                             {
   6:                                   multiplier = 7;
   7:                             }
   8:                             Else
   9:                             {
  Ten:                                   multiplier = 10;
  One:                             }
  :                             return num * multiplier;
  :                         };

X.2 Block Overview

Block provides us with a way to embed function code in a general sentence, and in other languages there are similar concepts called "closure", but in order to match Objective-c's example, we call this usage "block"

function of x.2.1 Block

Block is an inline function with anonymous functionality, which has the following characteristics:

As a general function can have parameters with the form.

Has a callback value.

The defined lexical scope (lexical scope) state can be retrieved.

You can optionally modify the state of the lexical scope.

Note: The lexical scope (lexical scope) can be imagined as a block in the middle of a function of two braces, which, when executed, will put this chunk into a stacked memory, and the declared variables in this block are like the area variables we often hear. When we say that block can retrieve the state of the same lexical scope, you can imagine that the block variable and other regional variables are the same level of regional variables (in the same layer of the stack), and the contents of the block can be read to other regional variables at his level.

We can either copy a block or throw it into another thread, basically although block can be used in the development of iOS programming, it can also be used in objective-c, but in the definition of the system, Block will always be considered a Objective-c object.

x.2.2 Block's use time

Blocks are typically used to represent and simplify a small piece of code, which is particularly well-suited for creating some program fragments that are executed synchronously, encapsulating small jobs, or calling back paging (callback) when a job is completed.

Blocks are heavily used to replace traditional delegate and callback in the new iOS API, and the new API will be heavily used for blocks based on the following two reasons:

You can write directly in the code, and so on to execute the program, directly the code into the function of the parameters passed into the function, which is the new API most commonly used block.

can access the regional variables, in the traditional callback implementation, if you want to access the region variable to be encapsulated in a variable structure to use, and block is convenient to directly access the regional variables.

X.3 Declaration and establishment of block

x.3.1 Declaration block Reference (Reference)

The block variable stores a block reference, and we declare it in a way similar to the declaration indicator, where the block variable refers to a function, and the indicator uses "*",block to declare it using "^", and here are some valid block declarations:

   
   2:void (^blockreturningvoidwithvoidargument) (void);
   
   4:int   (^blockreturningintwithintandchararguments) (int, char);
   
   6:void (^arrayoftenblocksreturningvoidwinintargument[) (int);
   
   
   
  
  
  12:     
  :     onefrom = ^ (int anint)
  :                 {
  15:                     
  :                 };

x.3.3 Whole-domain block

I can declare a whole domain block in the file, please refer to the following example:

   1:int globalint = 0;
   2:int (^getglobalint) (void) = ^ (void) {return globalint;};

X.4 Block and variables

In the next section we will describe the interaction between block and variable.

Patterns of x.4.1 variables

We can encounter the types of variables that we normally encounter in a function block:

The global variable, or static local variable.

L whole-domain functions.

L Regional variables and parameters passed in by the enclosing domain (enclosing scope).

In addition to the above, the block supports two additional variables:

__block variables can be used within a function, and these variables can be modified in the block.

The import constant (const imports).

In addition, in the implementation of the method, the block can use the OBJECTIVE-C entity variable (instance variable).

The following rules apply to the use of variables in the block:

You can access global variables and static variables in the same domain (enclosing lexical scope).

You can access the parameters of the incoming block (in the same way as the parameters passed in the function).

Regional variables in the same domain will be treated as constants (const) in the block.

You can access variables that use __block as modifiers in the same field.

The area variables declared in the block are used in the same way as the normal function using the regional variables.

The following example shows how a zone variable (3rd above) is used:

   1:int x = 123;
   2:void (^printxandy) (int) = ^ (int y)
   3:     {
   
   5:     };
   6://will be printed 123 456
   7:     Printxandy (456);
   
   
  10:int x = 123;
  11:void (^printxandy) (int) = ^ (int y)
  12: {
  All:     //The following line is wrong, because X is a constant in this cannot be modified.
  :     x = x + y;
  15:     
  :     };

If you want to modify the above variable x in the block, you must add the X declaration plus the modifier word __block, please refer to the next section for an introduction.

x.4.2 __block Type variables

We can make this variable from read-only to readable and write by placing a variable that is imported into block from the outside, but one limitation is that the variable passed in memory must be a variable that occupies a fixed-length memory, __ Block modifiers cannot be used for variable-length variables such as variable-length arrays, refer to the following example:

   1://plus __block modifier, so it can be modified in block.
   2: __block int x = 123;
   3:void (^printxandy) (int) = ^ (int y)
   4:     {
   5:         
   
   7:     };
   8://will be printed 579 456
   9:     Printxandy (456);
  Ten://x will become 579;
  
  
  13:extern Nsinteger Counterglobal;
  14:static Nsinteger counterstatic;
  15: {
  16:nsinteger localcounter = 42;
  : __block char Localcharacter;
  18:void (^ablock) (void) = ^ (void)
  :     {
  :         + + Counterglobal;//can be accessed.
  +:         + + counterstatic;//can be accessed.
  22:counterglobal = Localcounter; The localcounter is immutable when the block is built.
           localcharacter = ' a ';//Set the Localcharacter variable defined outside.
  :     };
  :     ++localcounter;//The value in the block that will not be affected.
  :     localcharacter = ' B ';
  :     Ablock ();//execute block contents.
  28://After execution, Localcharachter will become ' a '
  29:}

IOS block--in Lan Yi education

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.