作为本地变量:
格式:
returnType (^blockName)(paramType param...) = ^returnType(paramType param...) {
return ...
};
例如:
NSInteger (^getSum)(NSInteger a, NSInteger b) = ^NSInteger(NSInteger a, NSInteger b) {
return a + b;
};
NSLog(@"%ld", getSum(1, 2)); //打印3
作为属性
格式:
@property (nonatomic, copy) returnType (^blockName)(paramType param);
例如:
@property (nonatomic, copy) void (^blockName)(NSString *paramName);
作为方法参数
格式:
- (void)someMethodThatTakesABlock:(returnType (^)(paramType param))blockName;
例如:
- (void)doSomethingWithBlock:(void(^)(NSString *name))block {
}
用作typedef
格式:
typedef returnType (^TypeName)(paramType param);
TypeName blockName = ^returnType(parameters) {...};
例如:
typedef NSInteger (^GetSumWithDef)(NSInteger a, NSInteger b);
GetSumWithDef block = ^NSInteger(NSInteger a, NSInteger b) {
return a + b;
};
NSLog(@"%ld", block(2, 2)); //打印4
网友评论