[英]Objective-C Block: return __block variable from block inside
OK, here is the code. 好的,这是代码。
NSObject* (^executableBlock)(void) = ^NSObject*() {
__block NSObject *refObj = nil;
[Utility performAction:^() {
if (conditionA)
refObj = fooA;
else
refObj = fooB;
};
return refObj;
};
NSObject *result = executableBlock(); // result is nil
After executing the executableBlock, the result is nil and performAction block didn't be executed immediately and returned my expected value. 执行了executeBlock之后,结果为nil,并且performAction块没有立即执行,并返回了我的期望值。
I know performAction block is executed within another thread and using the shared nil pointer refObj. 我知道performAction块是在另一个线程中执行的,并使用共享的nil指针refObj。 Refer to Working with Blocks .
请参阅使用块 。
Here is my through, if I use GCD to call the performAction block and wait for its finish, how to rewrite it? 这是我的贯穿过程,如果我使用GCD调用performAction块并等待其完成,该如何重写它? Thanks!
谢谢!
I would considering the following re-structure: 我会考虑以下重组:
__block NSObject * result;
void (^executableBlock)(NSObject *) = ^void (NSObject * obj)
{
[self performAnActionWithBlock:^(BOOL success)
{
if (success) {
result = obj;
NSLog(@"results: %@", result);
}else{
result = nil;
}
}];
};
executableBlock(@"Hello");
//where:
-(void)performAnActionWithBlock:(void(^)(BOOL))block{
block(YES);
}
You should then be able to call result
from elsewhere 然后,您应该可以从其他地方调用
result
void (^executableBlock)(NSObject*) = ^(NSObject *arg) {
[Utility performAction:^(NSObject *arg) {
if (conditionA)
arg = fooA;
else
arg = fooB;
}];
}; };
__block NSObject *result = nil; __block NSObject * result = nil;
executableBlock(result); executableBlock(结果); // result will be changed in block
//结果将在块中更改
By using semaphore, you can wait until a block is done. 通过使用信号量,您可以等到块完成为止。
But completion-block may be suitable in your case, i think. 但我认为,完成模块可能适合您的情况。
NSObject* (^executableBlock)(void) = ^NSObject*() {
__block NSObject *refObj = nil;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[self performAction:^() {
if (conditionA)
refObj = fooA;
else
refObj = fooB;
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return refObj;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.