Simple understanding of block in Objective-c

Source: Internet
Author: User

Like the closure in JS, anonymous functions in Java, C # delegates, you can pass Func as a parameter:

Statement of the 1.Block

The definition of block is similar to the declaration of a function, which is to change the function name to (^blockname). The following is the code for the block declaration.

With a return value.

int (^sumblock) (intint);

With no return value

void (^myblock) (intint);

2. Assign values to block blocks

Assign a value to the declared block. The value of the block is a function body, assigning a value to a block block in two ways, one at the time of Declaration, and one declared in the assignment.

Declare the re-assignment first

//Declaration of a code blockvoid(^myblock) (int,int); //assigning values to code blocksMyblock = ^ (intAintb) {    //Test + +; //ErrorNSLog (@"Main_test =%d", test); //blockvar++ do not error;Blockvar + +; NSLog (@"Blockvar =%d", Blockvar); intsum = a +b; NSLog (@"A + b =%d", sum);};

Assigning values at the time of declaration

int (^sumblock) (intint) = ^ (intint  b) {    int sum = a + b;     return sum;};

3. Call Block

The use of the block is the same as the normal function, and the method is called as follows:

// Call the code block and receive the return value int sum = sumblock (+);

4. Pass the block as a parameter to the function

// use code blocks as function arguments void blockfunction (int (^myblock) (intint)) {    int sum = Myblock (ten);    NSLog (@ "fun_sum =%d", sum);}  

5. Using local variables and global variables in code blocks

We can access and modify the global variables in the block, but we can only access the local variables, and if we want to modify them, we can add the keyword __block when we declare the local variables.

The code is as follows

int 0;

Simple understanding of block in objective-c

Related Article

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.