Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

ios - Is there any way to "wait here..." in code - just like an empty loop?

Consider this code:

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

Note that this all happens ON THE SAME THREAD - we do not want to go to another thread.

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

otherStuff would set self.someFlag to true, when otherStuff is finally finished.

This works perfectly and there's no problem with it at all -- except that it's lame to burn up the processor like that with the empty loop!!

Quite simply, is there a way to say something like ..

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

Rather than just while(!self.someFlag){}

(Note the alternative is to "chain" the procedures ... so at the end of "otherStuff", you and all the other programmers have to "just know" that you have to next call "moreStuff", regardless of how otherStuff plays out, etc. Of course, that is very messy when you have to add new procedures or change the order of things.) Cheers!!

BTW there are already two excellent answers below regarding the situation when you want DIFFERENT THREADS.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...