好的,这是代码。
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
执行executableBlock后,结果为nil,并且没有立即执行performAction块并返回我的预期值。
我知道performAction块是在另一个线程中执行的,并使用共享的nil指针refObj。请参阅Working with Blocks。
这是我的通过,如果我使用GCD调用performAction块并等待其完成,如何重写它?谢谢!
答案 0 :(得分:0)
我会考虑以下重组:
__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);
}
然后,您应该可以从其他地方拨打result
答案 1 :(得分:0)
void (^executableBlock)(NSObject*) = ^(NSObject *arg) {
[Utility performAction:^(NSObject *arg) {
if (conditionA)
arg = fooA;
else
arg = fooB;
}];
};
__阻止NSObject * result = nil;
executableBlock(结果); //结果将在块
中更改答案 2 :(得分:0)
通过使用信号量,您可以等到一个块完成 但是,我认为,完成块可能适用于您的情况。
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;
};