Search code examples
iosobjective-cblock

How to return current method in GCD block?


Here is my code:

- (void)viewDidLoad {
    [super viewDidLoad];

    [self testGCD];
}

- (void)testGCD {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"1");
        return;
    });
    NSLog(@"2");
}

The console printed 1 and 2.

What I want is only to print 1 the first time. I think maybe the return is not returning from the method, but instead from the block.

Is there any way I can return from the current method in this GCD block?


Solution

  • If you see the definition of dispatch_once then you gonna see that they are using DISPATCH_EXPECT to compare the onceToken. You can also use if (onceToken != -1) but DISPATCH_EXPECT optimises the code by telling the compiler that the probability of onceToken == -1 is much much higher. This is called Branch Prediction

    - (void)testGCD {
      static dispatch_once_t onceToken;
      if (DISPATCH_EXPECT(onceToken, ~0l) != ~0l) {
        dispatch_once(&onceToken, ^{
          NSLog(@"1");
          return;
        });
      }
      else {
        NSLog(@"2");
      }
    }