How can I retrieve a return value from a completion block?

后端 未结 1 1108
半阙折子戏
半阙折子戏 2020-11-28 08:28

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 met         


        
相关标签:
1条回答
  • 2020-11-28 08:52

    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);
        }];
    }
    
    0 讨论(0)
提交回复
热议问题