简体   繁体   中英

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.

I know performAction block is executed within another thread and using the shared nil pointer 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? 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

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

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

};

__block NSObject *result = nil;

executableBlock(result); // 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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM