title: Core Data: How to get a notification when document is saved?
body: <p>I have noticed that when I call</p>
  
  <pre><code>[context save:nil];
  </code></pre>
  
  <p>the saving doesn't occur instantly. I tested that when I try to save and quit the app in one or two seconds. It only works if I keep the app open for 5+ seconds or so.</p>
  
  <p>I have 2 questions:</p>
  
  <ul>
  <li>How can I know when the save is complete? A simple NSLog() will be enough, just for testing purposes.</li>
  <li>Can I force a save? Should I?</li>
  </ul>
  
  <p><strong>Testing if [context save] is synchronous</strong></p>
  
  <p>I have tested that many times and this is not the behavior that I'm getting. If I have this code:</p>
  
  <pre><code>[context save:nil]
  NSLog(@"Saved");
  </code></pre>
  
  <p>I see the "Saved" log, quit the app, and when I launch it again and try to fetch the data - nothing there. <strong>This doesn't happen if I wait about 5-10 seconds after I see the "Saved" message.</strong> </p>
  
  <p>Thoughts?</p>
  
  <p><strong>Some code</strong></p>
  
  <pre><code>- (void)storeSales:(NSArray *)sales {
      NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
      [formatter setDateFormat:@"EE LLLL d HH:mm:ss Z YYYY"];
  
      for (NSDictionary *saleDictionary in sales) {
          Sale *sale = [NSEntityDescription insertNewObjectForEntityForName:@"Sale" inManagedObjectContext:self.context];
          sale.productName = [saleDictionary objectForKey:@"description"];
          sale.date = [formatter dateFromString:[saleDictionary objectForKey:@"occured_at"]];
  
          NSLog(@"Stored new sale in database.");
      }
  
      [self.context save:nil];
  }
  </code></pre>
  
  <p><strong>How I setup the UIManagedDocument</strong></p>
  
  <pre><code>@property (nonatomic, strong) UIManagedDocument *document;
  @property (nonatomic, strong) NSManagedObjectContext *context;
  
  ...
  
  NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
  url = [url URLByAppendingPathComponent:@"SalesBot Database"];
  self.document = [[UIManagedDocument alloc] initWithFileURL:url];
  
  if (![[NSFileManager defaultManager] fileExistsAtPath:[self.document.fileURL path]]) {
      [self.document saveToURL:self.document.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {}];
  } else if (self.document.documentState == UIDocumentStateClosed) {
      [self.document openWithCompletionHandler:^(BOOL success) {}];
  }
  
  self.context = self.document.managedObjectContext;
  </code></pre>
  
  <p><strong>UPDATE 1</strong></p>
  
  <p>I tried using NSNotificationCenter to receive NSManagedObjectContextDidSaveNotification - but - I'm receiving it twice! Once right after [context save:nil] and again 5-10 seconds later!</p>