Go to IOS development-block usage explained

Source: Internet
Author: User

1. Block action:

Block is used to encapsulate a piece of code that can be executed at any time;

    • A block can be used as a function parameter or as a return value for a function, and it can have either an input parameter or a return value.
    • Apple's official proposal to use block as much as possible. In multi-threaded, asynchronous tasks, collection traversal, collection sorting, animation transitions with a lot of
2. Definition of BLOCK:
int (^MySum)(intint) = ^(intint b) {       return a+b; };

As the above code defines a blocks object called MySum, it has two int parameters and returns an int. The right side of the equation is the concrete implementation of blocks

Block can access local variables, but cannot modify:

intsum10;?int (^MyBlock)(int) = ^(int num) {      sum++;//编译报错      returnsum; };

Add keywords If you want to modify:

__block __block int sum = 10;

    • Defines the function pointer int (*MYFN) ();
      Call function pointer (*MYFN) (10, 20)

    • Definition Blockint (^myblocks) (int,int);
      Call Blocks Myblocks (10, 20);

    • Define the variable at the same time as the declaration, then assign the value

int (^MySum)(int,int) = ^(int a,int b) {       return a + b;};

D. You can also first declare the type with a TypeDef, and then define the variable to assign the value

typedefint (^MySum)(int,int);MySum sum = ^(int a,int b) {       return a + b;};
3. Block access to external variables
    • External variables can be accessed within the block;
    • By default, the outer local variables cannot be modified inside the block;
    • Add the keyword _block to the local variable, and the local variable can be modified inside the block;
NetEase Interview Questions:

When does 13.__block use

14. Inside the block, add operations to the array, which need to be declared as __block?

15. Inside the block, modify the Nsinteger, whether the Nsinteger needs to be declared as __blcok

Go to IOS development-block usage explained

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.