最近开发过程中经常需要声明一个 block 变量,由于声明位置不同,block 变量的写法是不同,尴尬,发现自己总不能一次性写对!这里总结一下,后面就强记下来吧,让开发高效一些。
局部变量
returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};
举例:
int (^completion)(int a) = ^int(int a){
// ...
};
属性
@property (nonatomic, copy, nullability) returnType (^blockName)(parameterTypes);
举例:
@property (nonatomic, copy, nonnull) int (^completion)(int);
方法形参
- (void)doSomethingWithBlock:(returnType (^nullability)(parameterTypes))blockName;
举例:
- (void) doSomethingWithCompletion:(int (^_Nullable)(int))blockName;
方法实参
[someObject doSomethingWithBlock:^returnType (parameters) {...}];
举例:
[a doSomethingWithCompletion:^int (int) {
// ...
}];
类型定义
typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters) {
// ...
};
举例:
typedef int (^Handler)(int);
Handler handler = ^int(int) {
// ...
};
最后,Enjoy yourself!