Block块语法:
- Block块语法本质上和其他的变量类似。不同的是它存储的数据是一个函数体,类似于Java中的匿名方法,和C语言中的函数指针。你可以像调用其他标准函数一样,传入参数以后,可以得到返回值。
- (^)脱字符,是块语法的标记。按照我们熟悉的语法规定所定义的返回值及块的主体(也就是可以执行的代码)。
-
返回值类型 (^block名称) (参数类型, 参数类型,……) = ^(参数, 参数,……) { 函数实现 };int (^block) (int ,int) = ^(int a, int b) { return a + b; };
^返回值类型(参数列表) {函数体} 其中返回值类型 可以省略
// 使用block给数组进行排序 NSMutableArray *agesArray = [NSMutableArray arrayWithObjects:@"12", @"32", @"25", @"56", nil]; NSComparisonResult (^sortBlock) (id, id) = ^(id obj1, id obj2) { if ([obj1 intValue] > [obj2 intValue]) { return NSOrderedDescending; // 即1,返回真,就可以交换了 // Descending递减 } else if ([obj1 intValue] < [obj2 intValue]) { return NSOrderedAscending; // Ascending递增 } else { return NSOrderedSame; } }; // 将block作为参数传递给方法 [agesArray sortUsingComparator:sortBlock]; NSLog(@"%@", agesArray); [agesArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { if ([obj1 intValue] > [obj2 intValue]) { return NSOrderedDescending; } return NSOrderedSame; }]; NSLog(@"%@", agesArray); // 创建Person类,实例变量(_name, _score) 方法(setter和getter方法,初始化方法,便利构造器) // 在main.m文件中创建4名学生,放到数组中(可变不可变任意) // 使用Block的方法对数组进行排序 Person *person1 = [Person personWithAge:18 score:36]; Person *person2 = [Person personWithAge:12 score:72]; Person *person3 = [Person personWithAge:26 score:67]; Person *person4 = [Person personWithAge:47 score:56]; NSMutableArray *personArray = [NSMutableArray arrayWithObjects:person1, person2, person3, person4, nil]; [personArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { if ([obj1 getAge] > [obj2 getAge]) { return NSOrderedDescending; } return NSOrderedSame; }]; NSLog(@"%@", personArray); [personArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { if ([obj1 getScore] > [obj2 getScore]) { return NSOrderedDescending; } return NSOrderedSame; }]; NSLog(@"%@", personArray);
typedef int (^SumBlock) (int, int); SumBlock block = ^(int a, int b) { return a + b; };
// 使用typedef给block类型起一个别名 typedef int (^SumBlock) (int , int); SumBlock block = ^(int a, int b) { return a + b; }; int sum3 = block(4 , 6); NSLog(@"%d", sum3); // 求一个数的阶乘 typedef int (^Factorial) (int); Factorial block9 = ^(int a) { int b = 1; for (int i = 1; i <= a; i++) { b *= i; } return b; }; int x = block9(3); NSLog(@"%d",x);
// block与外部变量的关系 // block内部可以使用外部的变量 // 对于全局变量来说,可读可写 // 对于局部变量来捉,默认可读,不可写,如果想要修改局部变量,需要给局部变量添加__block 进行修饰 注意: 是两个下划线 __block int count = 55; void (^sayHello) (int) = ^(int c) { for (int i = 0; i < count; i++) { NSLog(@"Hello World"); } count = 2; NSLog(@"%d", count); }; sayHello(1); */