Is there any way to “wait here…” in code - just like an empty loop?

前端 未结 2 1661
轻奢々
轻奢々 2020-12-18 08:51

Consider this code:

[self otherStuff];
// \"wait here...\" until something finishes
while(!self.someFlag){}
[self moreStuff];

Note that thi

2条回答
  •  自闭症患者
    2020-12-18 09:03

    This is a solution using a semaphore, be careful not to introduce a deadlock - you need some way of telling your application something has finished, you can either do that using the NSNotificationCentre like you suggested but using a block is much easier.

    [self someOtherStuffWithCompletion:nil];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [self someOtherStuffWithCompletion:^{
      dispatch_semaphore_signal(semaphore);
    }];
    
    NSLog(@"waiting");
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    NSLog(@"finished");
    
    [self someOtherStuffWithCompletion:nil];
    

提交回复
热议问题