Block

一、Block 语法

1、^ 返回值类型 参数列表 表达式

例如:

^int (int count) {return count + 1;}

 

2、^  参数列表 表达式

省略返回值时,如果表达式中有return语句就使用该返回值的类型,如果表达式中没有return语句就使用void类型,表达式中含有多个return语句时,所有的返回值类型必须相同

^int (int count) {return count + 1;}

该源代码可省略为如下形式:

^ (int count) {return count + 1;}

该 Block 语法,返回 int 型返回值。

 

3、^  表达式

如果不使用参数,参数列表也可以省略

^void (void){printf("Block\n");}

该源代码可省略为如下形式:

^{printff("Block\n");}

 

二、 block类型变量

函数指针:int (*funcprt)(int) ;

block类型变量:int (^blk)(int);

声明block类型变量仅仅是将声明函数指针类型变量的 "*" 改为 "^",与一般 C 语言变量完成相同。

1、使用 Block 语法将 Block 赋值为 Block 类型变量。

int (^blk)(int) = ^(int count){return count + 1;};

2、作为函数的参数

void func (int (^blk)(int)){.... }

3、作为函数的返回值

int (^func())(){

    return ^(int count){return count +1;};

}

使用 typedef

typedef int(^blk_t)(int);

1、作为函数的参数

void func (blk_t){...}

2、作为函数的返回值

blk_t func1(){

    return ^(int count){return count +1;};

}

 

posted @ 2017-08-22 22:35  Rthena  阅读(168)  评论(0)    收藏  举报