[OC enhancement] defines and calls block data types, and transmits parameters to other applications.

Source: Internet
Author: User

(1) define methods and calls for pointers to functions:

#import <Foundation/Foundation.h>void test(){    NSLog(@"hello");}int main(int argc, const char * argv[]) {    @autoreleasepool {        //定义        void (*p1)()=test;        //使用        p1();    }        return 0;}

The definition of block is similar to that of block.

    //定义block,注意^以及末尾的分号;右边的函数体也不再需要函数名称,只要前面有myBlock即可    void (^myBlock)()=^{        NSLog(@"hello");    };    //调用,和函数类似    myBlock();

The difference between block and pointer to a function is that the latter can only put a function name behind it, rather than directly putting the code (function body) of the function behind it. The former makes up for this defect, which is equivalent to "encapsulating" the entire code block.


(2) block with Parameters

    //定义block,注意^以及末尾的分号;    int (^sum1)(int a,int b)=^int (int a,int b){        return a+b;    };    //调用,和函数类似    NSLog(@"%d",sum1(5,6));

(3) Since it is a data type, it can also be passed as a parameter.


(4) If you need to change the variable outside the block in the block code, add the _ block keyword before the variable.


[OC enhancement] defines and calls block data types, and transmits parameters to other applications.

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.