OBJECTIVE-C (13) code blocks---block

Source: Internet
Author: User

    • Block type

Block is a data type that is widely used in iOS development and is highly recommended by Apple, which functions like a function pointer in C.

^ is a unique symbol of block.

The implementation code for the block is included in the {}.

In most cases, the inline form is defined and used.


void (^demoblock) () = ^ {NSLog (@ "demo Block");} Int (^sumblock) (int, int) = ^ (int x, int y) {return x + y;}

Block usage is similar to the use of function pointers

Int (^sumblock) (int, int) = ^ (int a, int b) {return a>b?a:b;} int c = Sumblock (10, 20); NSLog (@ "c=%d", c);


External variables can be accessed inside the block

External local variables, block internal cannot be modified, global variables can be.

If the local variable uses the __block declaration, it can be modified internally.

int a = 10;__block int b = 20;void (^myblock) () Myblock = ^ {NSLog (@ "a=%d", a); b = 20;} Myblock ();

In fact, a local variable is copied when the block is defined (copy)


The importance of block: it is very convenient to handle asynchronous tasks, which is also the difficulty of block application



This article is from the "Teacheran" blog, make sure to keep this source http://annmeng.blog.51cto.com/3321237/1745694

OBJECTIVE-C (13) code blocks---block

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.