Understanding and use of block in iOS development

Source: Internet
Author: User

  1. Introduction
    • We can think of block as an anonymous function of objective-c. Block allows developers to pass arbitrary statements as data between two objects, often more intuitively than referencing functions defined elsewhere. In addition, the implementation of block is closed (closure), but it is easy to get the relevant state information of the context.
    • Blockis a block of code that is similar in nature to variables. The difference is that the code block stores the data as a function body. Useblock, you can pass in parameters like any other standard function, and get the return value
    Block Format:
    a: The return value type of block, can be null (void); B: Block object name, can be understood as variable name; ^: The syntax tag of the block, declaring B as a block object; C: first parameter type d: Second type of parameter name1,name2: The name of the parameter; {}: The subject part of the block code blocks.  Example:
    int (^myblock) (int,int) = ^ (intint  num2) {        return num1 + num2;    };    NSLog (@ "%d", Myblock (5,4
        • Printing results:9.
  2. Define and use
    1. Defines a block with no return value and no parameters
      • // 1. Define a block with no return value and no reference    void (^BLOCK1) () = ^() {        NSLog (@ " no block returned without reference");    };    Block1 ();
    2. Define no return value, parameter block
      • // 2. Define a block with no return value and parameters    void (^BLOCK2) (int) = ^ (int  a) {        NSLog (@ "%d", a);    };    Block2 (2);
      1. Defines a block that returns a value of OC object
        •  //  3. Defines a block  with a return value of OC object NSString * (^BLOCK3) (NSString *) = ^ (NSString *string   string  = [NSString stringwithformat:< Span style= "color: #800000;" >@ " %@_%@  " , , ";  return  string  ;    }; NSLog ( @ " %@  , Block3 (@"   I am the string  "));
    • From the above, the definition of a block variable is equivalent to defining a function that executes the code in its principal block {} Only when the block is called.
  3. Use of __block keywords
    • In block code blocks, you cannot modify variables defined outside theand in GivingBlockWhen assigning a value, it is already in the code blockVariableMake a copy of the value()
        •  int  x = 5  ;  int  (^block4) (int ) = ^ (int   y) { int  z = x + Y;     return   Z;    }; NSLog ( @ " %d,%d   ", x +=5 , Block4 (5 )); 

          The value printed is 10,10;

        • Parse: The variable x is defined outside the block, and the value of X is 5 (not modifiable) when the block code is compiled. So even if x + = 5 is executed so that the value of X becomes 10, but the X in the block code is still 5, the value of block (5) is 5+5=10.
    • After adding the __block keyword in front of the variable to be decorated, the variable is in block code blocks that can be changed (readable and writable) and the current value of the variable is taken when executing the code.
      • int 5 ;     int (^BLOCK4) (int) = ^ (int  y) {        int z = x + y;         return z;    };    NSLog (@ "%d,%d", x + =5, Block4 (5));

        The printed value is 10, 15;

  4. implements the transfer of values between objects as properties of the OC object
    • A block can be considered a variable, so it can be used as a property of an OC object
    • Requirements : Add a button to the Viewcontrler view, click the button mode to jump to the Firstviewcontroller view controller, andthe Firstviewcontroller two buttons on the view One is the direct dismiss mode jump to Viewcontroller, one is to change the background color of Viewcontroller and then dismiss modal jump back Viewcontroller
    • analysis :Firstviewcontroller is a view controller with Viewcontroller modal, which is changed in Firstviewcontroller Viewcontroller background color, it is necessary to do the reverse value.
    • implementation Steps:
      1. 1. In the FirstViewController.h file, define the block variable as the @property attribute
        • // The first step defines the block as the property attribute /*  */void(^colorblock) (Uicolor *color);

      2. In the firstviewcontroller.m file, the block is called in the button-click Trigger method.
          •  //  randomly generated colors  uicolor *color = [Uicolor colorwithred:arc4random ()%256 /255.0  green:arc4random ()%256 /255.0  Blue:arc4random ()%256 /1  ];  //  to the block. if   (Self.colorblock) {self.colorblock (color);}
            [Self Dismissviewcontrolleranimated:yes completion:nil];  
      3. In the viewcontroller.m file, instantiate the Firstviewcontroller object and execute block code.
        • Firstviewcontroller *FVC = [[Firstviewcontroller alloc] init]; // Execute block code blocks Fvc.colorblock = ^ (Uicolor *color) {    = color;};
    • Effect Show :

Understanding and use of block in iOS development

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.