实现一个将块用作回调的方法 [英] Implementing a method taking a block to use as callback
问题描述
我想写一个类似这样的方法:
I would like to write a method similar to this:
+(void)myMethodWithView:(UIView *)exampleView completion:(void (^)(BOOL finished))completion;
我基本上剥离了从 Apple 的 UIView
类方法之一中提取的语法:
I've basically stripped down the syntax taken from one of Apple's class methods for UIView
:
+ (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion;
并希望它像这样使用:
[myFoo myMethodWithView:self.view completion:^(BOOL finished){
NSLog(@"call back success");
}];
我的问题是如何实现这一点?如果有人可以指出我的正确文档,那将是很棒的,并且非常基本的示例将不胜感激(或 Stack Overflow 上的类似答案——我找不到).我仍然不太了解委托,无法确定这是否是正确的方法!
My question is how can I implement this? If someone can point me to the correct documentation that would be great, and a very basic example would be much appreciated (or a similar answer on Stack Overflow -- I couldn't find one). I still don't quite know enough about delegates to determine whether that is even the correct approach!
我已经在实现文件中放了一个粗略的例子,说明我希望它在实现文件中的内容,但由于我找不到信息,所以只能猜测了.
I've put a rough example of what I would have expected it to be in the implementation file, but as I can't find info it's guess work.
+ (void)myMethod:(UIView *)exampleView completion:(void (^)(BOOL finished))completion {
// do stuff
if (completion) {
// what sort of syntax goes here? If I've constructed this correctly!
}
}
推荐答案
你可以像调用普通函数一样调用块:
You can call a block like a regular function:
BOOL finished = ...;
if (completion) {
completion(finished);
}
这意味着使用您的示例实现一个完整的块功能将如下所示:
So that means implementing a complete block function using your example would look like this:
+ (void)myMethod:(UIView *)exampleView completion:(void (^)(BOOL finished))completion {
if (completion) {
completion(finished);
}
}
这篇关于实现一个将块用作回调的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!