1.申明一个本地变量
returnType (^blockName)(parameterTypes) = ^returnType(parameters){...}
例如
bool (^isEventBlock)(NSInteger num) = ^bool(NSInteger num){
if (num % 2 == 0)
return YES;
else
return NO;
};
2.申明一个属性
@property (nonatomic, copy, nullability) returnType (^blockName)(parameterTypes);
例如
@property (nonatomic, copy, nullability) bool (^evenBlock)(NSInteger num);
3.申明一个函数参数
-(void)someMethodThatTakesABlock:(returnType (^nullability)(parameterTypes)) blockName;
例如
- (void)filterNumsWithEvenBlock:(bool (^)(NSInteger num)) evenBlock;
- (void)filterNumsWithEvenBlock:(bool (^)(NSInteger num)) evenBlock
{
NSInteger num = 3;
evenBlock(3);
}
4.作为一个函数调用的参数
[someObject someMethodThatTakesABlock:^returnType (parameters){...}];
例如
[self filterNumsWithEvenBlock:^bool (NSInteger num){
if (num % 2 == 0 )
return YES;
else
return NO;
}];
5.重命名typedef
typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters){...};
例如
typedef bool (^EvenBlock)(NSInteger num);
EvenBlock evenBlock = ^bool (NSInteger num){
if (num % 2 == 0)
return YES;
else
return NO;
};