Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's often a bad approach to block the main thread, it will just make your app unresponsive, so why not do something like this instead?</p> <pre><code>NSArray *names; int namesIndex = 0; - (void)setup { // Insert code for adding loading animation [UIView animateWithDuration:1 animations:^{ self.view.alpha = self.view.alpha==1?0:1; } completion:^(BOOL finished) { names = @[@"John", @"Mary", @"Peter", @"Madalena"]; [self alterNames]; }]; } - (void)alterNames { if (namesIndex&gt;=names.count) { // Insert code for removing loading animation // C. Need to wait here until all iterations above have finished. return; } NSString *name = [names objectAtIndex:namesIndex]; [UIView animateWithDuration:1 animations:^{ self.view.alpha = self.view.alpha==1?0:1; } completion:^(BOOL finished) { name = @"saf"; // A. Something that takes a few seconds to complete. // B. Need to wait here until A is completed. namesIndex++; [self alterNames]; }]; } </code></pre> <p>I have just used [UIView animation...] to make to example fully functional. Just copy and paste into your viewcontroller.m and call [self setup]; Of course, you should replace that with your code.</p> <p>Or if you want:</p> <pre><code>NSArray *names; int namesIndex = 0; - (void)setup { // Code for adding loading animation [someThing retrieve:@"foo" completion:^ { names = @[@"John", @"Mary", @"Peter", @"Madalena"]; [self alterNames]; }]; } - (void)alterNames { if (namesIndex&gt;=names.count) { // Code for removing loading animation // C. Need to wait here until all iterations above have finished. return; } NSString *name = [names objectAtIndex:namesIndex]; [someObject lookupName:name completion:^(NSString* urlString) { name = @"saf"; // A. Something that takes a few seconds to complete. // B. Need to wait here until A is completed. namesIndex++; [self alterNames]; }]; } </code></pre> <p>Explanation:</p> <ol> <li>Start everything by calling [self setup];</li> <li>A block will be called when someThing retrieves "foo", in other words, <strong>it will wait</strong> until someThing retrieves "foo" (and the main thread won't be blocked)</li> <li>When the block is executed, alterNames is called</li> <li>If all the items in "names" have been looped through, the "looping" will stop and C could be executed.</li> <li>Else, lookup the name, and <strong>when it's done</strong>, do something with it (A), and because it happens on the main thread (You haven't said anything else), you could do B there too.</li> <li>So, <strong>when A and B is complete</strong>, jump back to 3</li> </ol> <p>See?</p> <p>Good luck with your project!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload