[IOS] What is the meaning of __block in obnjective-c?

Source: Internet
Author: User

The __block tag tells the compiler that this variable needs special handling in the block.


In general, the value of the variable used in the block is copied, so the modification of the variable itself does not affect the actual value of the variable. And when we mark it with __block, it means that the change in the block is also effective outside the block.


Refer to https://developer.apple.com/library/ios/documentation/cocoa/Conceptual/Blocks/Articles/bxVariables.html for details, This is Apple's official explanation for block.


Now let's look at an example:


extern Nsinteger counterglobal;static Nsinteger counterstatic; {    Nsinteger localcounter =;    __block Char Localcharacter;    void (^ablock) (void) = ^ (void) {        ++counterglobal;        ++counterstatic;        Counterglobal = Localcounter; Localcounter fixed at block creation        Localcharacter = ' a ';//sets Localcharacter in enclosing scope    };    ++localcounter; Unseen by the block    localcharacter = ' B ';    Ablock (); Execute the Block    //Localcharacter now ' a '}


In the above code, both Localconter and Localcharacter are modified in blocks, but only localcharacter modifications in the block are valid because the __block tag plays a role. Changes to the Localcharacter in the block are also visible outside the block.


[IOS] What is the meaning of __block in obnjective-c?

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.