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

前端 未结 2 1660
轻奢々
轻奢々 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

    I would suggest to use a NSOperationQueue and to wait for all tasks until they are finished at specific points. Something like that:

    self.queue = [[NSOperationQueue alloc] init];
    
    // Ensure a single thread
    self.queue.maxConcurrentOperationCount = 1;
    
    // Add the first bunch of methods
    [self.queue addOperation:[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(method1) object:nil]];
    [self.queue addOperation:[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(method2) object:nil]];
    [self.queue addOperation:[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(method3) object:nil]];
    
    // Wait here
    [self.queue waitUntilAllOperationsAreFinished];
    
    // Add next methods
    [self.queue addOperation:[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(method4) object:nil]];
    [self.queue addOperation:[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(method5) object:nil]];
    
    // Wait here
    [self.queue waitUntilAllOperationsAreFinished];
    

    HTH

提交回复
热议问题