最近開發過程中經常需要聲明一個 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!