1.定义Block
/* 回传void ,参数也是void 的block*/
void (^blockReturningVoidWithVoidArgument)( void );
/* 回传整数,两个参数分别是整数和字元型态的block*/
int (^blockReturningIntWithIntAndCharArguments)( int , char );
/* 回传void ,含有10 个block 的阵列,每个block 都有一个型态为整数的参数*/
void (^arrayOfTenBlocksReturningVoidWinIntArgument[ 10 ])( int );
/* 定义对象方法使用block,block中需要传入一个NSString参数,返回void*/
- (void)testBlockWithParam:(void (^)(NSString *text))block;
声明block局部变量:
returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};
声明block属性:
@property (nonatomic, copy) returnType (^blockName)(parameterTypes);
接收block作为一个方法参数:
- (void)aMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;
在方法调用中将block作为一个参数传递:
[someObject someMethodThatTakesABlock: ^returnType (parameters) {...}];
定义一个block类型:
typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters) {...};
2.使用Block
- (void)testBlockWithParam:(void (^)(NSString *text))block{ NSLog(@"start test"); // 定义参数x,在testx中使用 int x = ; int (^testx)(int) = ^(int num2){ return x+num2; }; NSLog(@"use x:%d",testx()); // 使用__block标示符,定义一个可在block中修改值的参数y __block int y = ; int (^testy)(int) = ^(int num2){ if (num2 > ) { y = ; }else{ y = ; } return y+num2; }; NSLog(@"when num2 > 10,sum = %d",testy()); NSLog(@"when num2 <= 10,sum = %d",testy()); [NSThreadsleepForTimeInterval:1.0f]; block(@"success"); }