ios 实现一个将块用作回调的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7180552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implementing a method taking a block to use as callback
提问by Chris
I would like to write a method similar to this:
我想写一个类似于这样的方法:
+(void)myMethodWithView:(UIView *)exampleView completion:(void (^)(BOOL finished))completion;
I've basically stripped down the syntax taken from one of Apple's class methods for UIView
:
我基本上剥离了从 Apple 的类方法之一中获取的语法UIView
:
+ (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion;
And would expect it to be used like so:
并希望它像这样使用:
[myFoo myMethodWithView:self.view completion:^(BOOL finished){
NSLog(@"call back success");
}];
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!
我的问题是我该如何实施?如果有人可以指出我的正确文档,那将是很棒的,并且非常感谢一个非常基本的示例(或 Stack Overflow 上的类似答案——我找不到)。我仍然不太了解代表来确定这是否是正确的方法!
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!
}
}
回答by omz
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);
}
}
回答by Chaitanya Gupta
回答by Mohammad Abdurraafay
If you're specially looking for a doc, to create custom method using blocks, then the following link is the one which explains almost everything about it. :)
如果您正在专门寻找文档以使用块创建自定义方法,那么以下链接几乎解释了有关它的所有内容。:)
http://developer.apple.com/library/ios/documentation/cocoa/Conceptual/Blocks/Articles/bxUsing.html
http://developer.apple.com/library/ios/documentation/cocoa/Conceptual/Blocks/Articles/bxUsing.html
I happen to answer quite a same question recently, have a look at this: Declare a block method parameter without using a typedef
最近我碰巧回答了一个完全相同的问题,看看这个:Declare a block method parameter without using a typedef