我想定义一个方法,该方法将包含该 block 作为参数,但 block 应该在该方法的完成
时运行。
例如:
[picker dismissViewControllerAnimated:YES completion:^{
imageThumb = pickedImage;
imageViewThumb.image = imageThumb;
}];
请看看我做了什么。
我在 .h
文件中声明了该方法 -
-(void)resizeImageForSmoothness: (int) imageSmoothness completion: (void (^)(void))completion;
我在.m
文件中实现了它-
-(void)resizeImageForSmoothness:(int)imageSmoothness completion: (void (^)(void))completion
{
// Here i performed my image resizing activity
}
我的代码如何知道该方法已完成,然后运行完成 block ?
我们如何声明和定义这样的方法?
最佳答案
如何存储 block 取决于你如何做你的事情。如果它是同步操作(即该方法会阻塞,直到整个操作完成),您只需像函数一样调用它:
- (void)fooWithHandler:(void(^)())handler
{
// Do things.
handler();
}
如果操作是异步的,您可能希望将 block 存储在变量甚至字典中。在这种情况下,您需要复制该 block 。您可以通过低级 Block_copy
和 Block_release
C 函数来完成此操作,但您也可以将 block 视为 Objective-C 对象! (出于某种原因,Xcode 不提供自动完成功能。)
@interface MyClass {
void (^myHandler)();
}
- (void)fooWithHandler:(void(^)())handler
@end
@implementation MyClass
- (void)fooWithHandler:(void(^)())handler
{
myHandler = [handler copy];
// Do things.
// Then, when you're done (this is probably in another method):
if (myHandler) {
myHandler();
myHandler = nil;
}
}
@end
关于ios - 如何使方法具有可执行 block 作为参数,该参数应在 objective-c 中的方法完成时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20952027/