如何从完成块中检索返回值? [英] How can I retrieve a return value from a completion block?
问题描述
是否可以在主线程上运行完成块?
Is it possible to run a completion block on the main thread?
例如,我有一个方法返回一个值:
For example, I have one method which returns a value:
- (int)test
{
/* here one method is called with completion block with return type void */
[obj somemethodwithcompeltionblock:
{
/* here I am getting my Int which I want to return */
}
];
}
但是我看不到如何从完成内返回整数值阻止作为此方法的结果,因为完成块在后台线程上运行。
but I can't see how to return the integer value from within the completion block as the result of this method, because the completion block runs on a background thread.
我该怎么做?
推荐答案
您缺少一些关于使用块进行异步开发的基础知识。除了自己的范围之外,您不能从任何地方返回调度块。将每个块视为自己的方法,而不是内联代码。
You're missing some basics about asynchronous development with blocks. You can't have a dispatched block return from anywhere but its own scope. Think of each block as its own method, instead of inline code.
我认为您正在寻找的东西与此类似......
I think what you're looking for is something similar to this...
- (void)testWithHandler:(void(^)(int result))handler
{
[obj somemethodwithcompeltionblock:^{
int someInt = 10;
dispatch_async(dispatch_get_main_queue(), ^{
handler(10);
});
}
];
}
- (void)callSite
{
[self testWithHandler:^(int testResult){
NSLog(@"Result was %d", testResult);
}];
}
这篇关于如何从完成块中检索返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!