Block块使用

2015-10-25  本文已影响126人  smile丽语

block

// 基本用法一:1.定义无参数无返回值的Block代码块

// void:无返回值 ():无参数

void (^printBlock)() = ^() {

NSLog(@"这是无参数无返回值的Block块");

};

// 调用该无参数无返回值的Block块

printBlock();

// 基本用法二:2.定义有参数无返回值的Block代码块

// (int):数据类型  ^(int num):有参数,且数据类型也要有

void (^printNumBlock)(int) = ^(int num) {

NSLog(@"这是有参数无返回值的Block块, 传入的参数是:%d", num);

};

// 调用该有参数无返回值的Block块

printNumBlock(10);

// 基本用法三:3.定义有参数有返回值的Block代码块

// int:有返回值,返回数据类型为int的值,⚠️不要加括号

// ^(int num):有参数,且数据类型也要有

int (^printCountBlock) (int) = ^(int num) {

NSLog(@"这是有参数有返回值的Block块,传入的参数是:%d", num);

return num * 9;

};

// 调用该有参数有返回值的Block块

int consequence = printCountBlock(8);

NSLog(@"这是有参数有返回值的Block块,返回的值是:%d", consequence);

为什么用block? 和函数有很多相似之处,但是绝对绝对不是函数。

^{

语句体;

};

PS: // myblock是block类型的变量

void (^myblock)() = ^{

NSLog(@"Hello, World!");

};

// 调用myblock函数

myblock();

函数是不允许嵌套定义的,也就是不允许在函数的定义里再去定义一个函数。

block可以在函数的定义里定义。

int(^mathBlock)(int x,int y);  mathBlock 是block类型的变量

typedef  int(^mathBlock)(int x,int y);  而现在mathBlock类型的别名是.block类型 int(^)(int x,int y);

typedef 的使用

1.int count;  count是整形类型的变量

2.typedef int count;  count是整形类型的别名。

3.count i; 那么i就是count类型的,也就是int类型的。

1.int(*math_t)(int, int);

math_t是什么? 是指向指针类型的变量 ,存放的是地址。函数的名字就是函数的入口地址.

2. typedef int(*math_t)(int, int);

3. math_t mt; mt是什么?变量。指针类型的变量。访问这个变量内容里的内容的时候,访问方式是函数类型。

PS: // 第二个有参block的使用

// typedef的使用 此时mathBlock类型的别名是.block类型 int(^)(int x,int y);

typedef int(^mathBlock)(int x,int y);

mathBlock mt;

mt = ^(int x, int y){

return x + y;

};

// 调用有参mathBlock函数

int result = mt(3, 5);

NSLog(@"result = x+y = %d", result);

block语句块可以访问可以访问block外局部变量,但是只能读取不能写; 如果想写入,需要在变量声明的前边加上__block声明。

int var_a = 20;

__block int var_b = 30;

block可以作为返回值类型

在主函数里: // 第三种

int a = 3; int b = 5;

int result2;

int mta;

TRMath *t = [[TRMath alloc] init];

// 调用process方法

mta = [t process:^int(int x, int y) {

return x + y;

} withInt:b otherInt:a];

result2 = [t process:^int(int x, int y) {

return x - y;

} withInt:b otherInt:a];

NSLog(@"a + b = %d", mta);

NSLog(@"b - a = %d", result2);

// 第四种

TRPerson *tp = [[TRPerson alloc] init];

// 调用getBlock方法

TRBlock bloc = [tp getBlock];

bloc();

上一篇 下一篇

猜你喜欢

热点阅读