Objective-C 块:return __block 来自块内部的变量

Objective-C Block: return __block variable from block inside

好的,这是代码。

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 block没有立即执行,返回了我期望的值。

我知道 performAction 块在另一个线程中执行,并使用共享的 nil 指针 refObj。参考Working with Blocks.

这是我的通过,如果我使用GCD调用performAction块并等待它完成,如何重写它?谢谢!

我会考虑以下重组:

    __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

void (^executableBlock)(NSObject*) = ^(NSObject *arg) {

[Utility performAction:^(NSObject *arg) {
     if (conditionA)
          arg = fooA;
     else
          arg = fooB;
}];

};

__block NSObject *result = nil;

可执行块(结果); // 结果将在块

中改变

通过使用信号量,您可以等到块完成。
但我认为 completion-block 可能适合你的情况。

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;
};