- // main.m
- /*
- block与函数的相似之处:
- * 都能封装一段代码
- * 都能接收参数
- * 都有返回值
-
- 函数的定义:
- * 无参数、无返回值
- void myFunction()
- {
- NSLog(@"没有参数、没有返回值的函数");
- }
- * 有参数、有返回值
- int sumFunction(int a , int b)
- {
- return (a+b)/2;
- }
-
- block的定义:
- * 无参数、无返回值
- void (^myBlock)() = ^(){
- NSLog(@"没有参数、没有返回值的block");
- };
- * 有参数、有返回值
- int (^sumBlock)(int , int) = ^(int a , int b){
- return (a+b)/2;
- };
-
- 用typedef定义新类型:
- typedef double (^NewBlockType)(double , double);
- NewBlockType averageBlock = ^(double a , double b){
- return (a+b)/2;
- };
- */
- #import <Foundation/Foundation.h>
- typedef double (^AverageBlock) (double , double); //用typedef宏定义来定义新类型AverageBlock
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
-
- void (^myBlock) (); //定义一个没有返回值,没有参数的block变量myBlock
- myBlock = ^(){
- NSLog(@"hello , world");
- };
-
- myBlock();
-
-
- int (^sumBlock) (int , int); //定义一个block变量sumBlock,接收2个int类型参数,返回int类型
- sumBlock = ^(int a , int b){
- return a+b;
- };
-
- int sum = sumBlock(12 , 53);
- NSLog(@"%d" , sum);
-
- AverageBlock averageBlock;
- averageBlock = ^(double a , double b){
- return (a+b)/2;
- };
- NSLog(@"%f" , averageBlock(23.6 , 642.4));
- }
- return 0;
- }
复制代码
|
|