I have just discovered completion blocks:
completion:^(BOOL finished){
}];
What do I need to do to have my own method take a completion block?
I have just discovered completion blocks:
completion:^(BOOL finished){
}];
What do I need to do to have my own method take a completion block?
1)定义自己的完成块,
typedef void(^myCompletion)(BOOL);
2)创建一个将完成块作为参数的方法,
-(void) myMethod:(myCompletion) compblock{
//do stuff
compblock(YES);
}
3)这就是你使用它的方式,
[self myMethod:^(BOOL finished) {
if(finished){
NSLog(@"success");
}
}];
您将块定义为自定义类型:
typedef void (^ButtonCompletionBlock)(int buttonIndex);
然后将其用作方法的参数:
+ (SomeButtonView*)buttonViewWithTitle:(NSString *)title
cancelAction:(ButtonCompletionBlock)cancelBlock
completionAction:(ButtonCompletionBlock)completionBlock
在代码中调用它时,它就像任何其他块一样:
[SomeButtonView buttonViewWithTitle:@"Title"
cancelAction:^(int buttonIndex) {
NSLog(@"User cancelled");
}
completionAction:^(int buttonIndex) {
NSLog(@"User tapped index %i", buttonIndex);
}];
如果需要触发块,只需调用completionBlock()
(块completionBlock
的本地副本的名称在哪里)。
块变量在语法上类似于 C 中的函数指针。
因为语法难看,它们通常是类型定义的,但是它们也可以正常声明。
typedef void (^MyFunc)(BOOL finished);
- (void)myMethod:(MyFunc)func
{
}
有关非 typedef,请参阅此答案: