Block in OC, OCBlock

Source: Internet
Author: User

Block in OC, OCBlock

Block encapsulates a piece of code that can be executed at any time

A Block can be used as a function parameter or return value, and it can contain an input parameter or return value.

Apple officially recommends using block as much as possible. It is widely used in multithreading, asynchronous tasks, set traversal, set sorting, and animation transfer.

I. Definition of Blocks:

Int (^ MySum) (int, int) = ^ (int a, int B ){

Return a + B;

};

Defines a blocks object named MySum. It has two int parameters and returns int. The right side of the equation is the specific implementation of blocks.

Block can access local variables, but cannot be modified.

Int sum = 10;

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

Sum ++; // compilation Error

Return num * sum;

};

If you want to modify it, add the keyword :__ block.

_ Block int sum = 10;

Ii. Define function pointers

Int (* myFn )();

Define Blocks

Int (^ MyBlocks) (int, int );

Call function pointer

(* MyFn) (10, 20 );

Call Blocks

MyBlocks (10, 20 );

3. Define variables while declaring and assign values

Int (^ MySum) (int, int) = ^ (int a, int B ){

Return a + B;

};

You can also declare the type first with typedef and then define the variable to assign values.

Typedef int (^ MySum) (int, int );

MySum sum = ^ (int a, int B ){

Return a + B;

};

 

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.