Is there a way to "wait here ..." in the code - like an empty loop?

Consider this code:

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

Please note that this all happens ONE THREAD - we do not want to go to another thread.

otherStuff can do things like connect to the cloud, get user input, etc., so it will take a lot of time and can follow many possible paths.

otherStuff sets self.someFlag to true when elseStuff completes.

This works fine, and no problem with it at all - except that it is limping to burn the processor with an empty loop !!

Pretty simple, is there a way to say something like ..

halt here, until (some message, interrupt, flag, boolean, whatever?)

Instead of just (! Self.someFlag) {}

( , "" ... "otherStuff" " ", "moreStuff", , otherStuff .. , , .) Cheers!!

, , .

+4
2

, , , - - , - , NSNotificationCentre, , .

[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];
+4

NSOperationQueue , . - :

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];

+1

Source: https://habr.com/ru/post/1526899/


All Articles