OC语言学习22-Block基本语法

来源:互联网 发布:ibatis sql注入 编辑:程序博客网 时间:2024/05/21 09:14

创建工程,在main.h中编写代码:

#import <Foundation/Foundation.h>

//自定义C语言函数

void test()

{

    printf("%s\n",__func__);

}


int main(int argc,const char * argv[]) {

    @autoreleasepool {

        //函数指针 *testPtr指针名称,第二个()是参数表

        //test表示将函数赋值给函数指针变量

        void (*testPtr)() =test;

        //调用函数

        test();

        //用函数指针调用

        testPtr();

        //定义block

        void(^testBlock)() = ^() {

            test();

            //这里还可以添加代码逻辑

            NSLog(@"info");

        };

        testBlock();

        //使用__block定义才能在块中更改变量

        int__block number = 10;

        

        //实现两个数求和 两个int型的型参

        int (^sumBlock)(int,int) = ^(int a,int b) {

            number = 15;//声明时没有用__block会报错

            return a + b;

        };

        //此时的number的值还是为10,因为还没有调用block

        NSLog(@"number = %d", number);

        int sum = sumBlock(12,20);

        NSLog(@"sum = %d", sum);

        //调用之后才能执行压栈操作,这时的number的值为15了。

        NSLog(@"number = %d", number);

    }

    return0;

}

打印结果:

test

test

test

2017-07-25 16:45:43.293516+0800 OC25-block基础语法[2296:113335] info

2017-07-25 16:45:43.293650+0800 OC25-block基础语法[2296:113335] number = 10

2017-07-25 16:45:43.293661+0800 OC25-block基础语法[2296:113335] sum = 32

2017-07-25 16:45:43.293669+0800 OC25-block基础语法[2296:113335] number = 15

Program ended with exit code: 0