title: Wait for async task to finish completion block before returning in app delegate
body: <p>I'm using a subclass of <code>UIManagedDocument</code> to use Core Data in my project. The point is for the subclass to return a singleton instance so that my screens can simply call it and the managed object context remains the same for all of them.</p>
  
  <p>Before using the <code>UIManagedDocument</code>, I need to prepare it by opening it if its file path already exists, or creating it if it doesn't yet. I created a convenience method <code>prepareWithCompletionHandler:</code> in the subclass to facilitate both scenarios.</p>
  
  <pre><code>@implementation SPRManagedDocument
  
  // Singleton class method here. Then...
  
  - (void)prepareWithCompletionHandler:(void (^)(BOOL))completionHandler
  {
      __block BOOL successful;
  
      // _exists simply checks if the document exists at the given file path.
      if (self.exists) {
          [self openWithCompletionHandler:^(BOOL success) {
              successful = success;
  
              if (success) {
                  if (self.documentState != UIDocumentStateNormal) {
                      successful = NO;
                  }
              }
              completionHandler(successful);
          }];
      } else {
          [self saveToURL:self.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
              successful = success;
  
              if (success) {
                  if (self.documentState != UIDocumentStateNormal) {
                      successful = NO;
                  }
              }
              completionHandler(successful);
          }];
      }
  }
  
  @end
  </code></pre>
  
  <p>What I'm trying to do is call this preparation method in my app delegate's <code>didFinishLaunchingWithOptions</code> and wait for the completion block to be executed BEFORE returning either <code>YES</code> or <code>NO</code> at the end. My current approach doesn't work.</p>
  
  <pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  {
      __block BOOL successful;
      SPRManagedDocument *document = [SPRManagedDocument sharedDocument];
  
      dispatch_group_t group = dispatch_group_create();
  
      dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
          [document prepareWithCompletionHandler:^(BOOL success) {
              successful = success;
          }];
      });
  
      dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
      });
  
      return successful;
  }
  </code></pre>
  
  <p>How can I wait until the completion handler in <code>prepareWithCompletionHandler</code> is called before returning <code>successful</code>? I'm really confused.</p>