IOS block use

Source: Internet
Author: User

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.

The block entity form is as follows:

^ (Incoming parameter column ) { behavior body };

1:block can access local variables, but cannot be modified.

int multiplier = 7;

Int (^myblock) (int) = ^ (int num) {

Multiplier ++;//Compile Error

return num * multiplier;

};

Add keywords If you want to modify: __block

__block int multiplier = 7;

Int (^myblock) (int) = ^ (int num) {

Multiplier ++;//Compile Error

return num * multiplier;

};

2: As a function parameter, blocks replaces the callback function or delegate in some sense. When a function is called, it is assumed that an event is triggered, and then the contents of the blocks run. This facilitates the integration of code and reading, you do not need to go everywhere to implement the delegation method.

3:block pointer is defined in this way:

Callback Value (^ name ) ( parameter column );

4:///5: You can modify the value of the Outa directly inside the block,
static int outA = 8;
__block int OutA = 8;
Int (^myptr) (int) = ^ (int a) {OutA = 5; return OutA + A;};
int RESULT3 = MYPTR (3); The value of result is 8 because Outa is a variable of type static
NSLog (@ "result=%d", RESULT3);

IOS block use

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.