title: performBlockAndWait creates deadlock
body: <p>I am writing a function that performs some CoreData stuff. I want the function to return only <em>after</em> all the CoreData operations have executed. The CoreData stuff involves creating an object in a background context, then doing some more stuff in the parent context:</p>
  
  <pre><code>+ (void) myFunction
      NSManagedObjectContext *backgroundContext = [DatabaseDelegate sharedDelegate].backgroundContext;
  
      [backgroundContext performBlockAndWait:^{
        MyObject *bla = create_my_object_in:backgroundContext;
  
        [backgroundContext obtainPermanentIDsForObjects:[[backgroundContext insertedObjects] allObjects] error:nil];
        [backgroundContext save:nil];
  
        [[DatabaseDelegate sharedDelegate].parent.managedObjectContext performBlockAndWait:^{
          [[DatabaseDelegate sharedDelegate].parent updateChangeCount:UIDocumentChangeDone];
  
          // Do some more stuff
          NSOperationQueue *queue = [[NSOperationQueue alloc] init];
          [queue addOperation:someOperation];
        }];
      }];
     return;
  }
  </code></pre>
  
  <p>I want the return to only happen after <code>[queue addOperation:someOperation]</code>.
  This seems to work most of the cases, but I have had one case when this function never returned. It seemed like it was deadlocked, and I suspect it is because of <code>performBlockAndWait</code>.</p>
  
  <p>My questions are:</p>
  
  <p>(1) Can someone explain why this deadlock occurs?</p>
  
  <p>and</p>
  
  <p>(2) What is the right way of achieving the same functionality? The requirement is that <code>myFunction</code> returns only after both blocks have been executed.</p>
  
  <p>Thank you!</p>