title: Core Data "Connection Invalid"
body: <p>So this sucks. Trying to populate a core data database with info from NSDictionaries.</p>
  
  <p>I open a UIManaged Document using the code below, the completion handler block then invokes a method which recursively populates a dictionary from an API and adds an entity for the database for each one.</p>
  
  <p>The database file is created just fine, the dictionary is populating fine, and the entity object is also populated, but for some reason the info is not writing to the database, although it has on occasion worked, I'm not sure if anything was different.</p>
  
  <p>I get a message in the console which says: </p>
  
  <p>"NSFileCoordinator: A surprising server error was signaled. Details: Connection invalid"</p>
  
  <p>whenever the methods openWithCompletionHandler or saveToURL:forSaveOperation:withCompletionHandler run.</p>
  
  <p>I can't understand why the code below doesn't work given that it's cut and pasted from the Stanford iphone course.</p>
  
  <p>I've tried deleting the app from the simulator but no difference. This has been wrecking my head for hours, any help appreciated, thanks.</p>
  
  <pre><code>+ (void)populateDatabase
  {
  // Get URL -&gt; "&lt;Documents Directory&gt;/&lt;TrailerDB&gt;" 
  NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
  
  url = [url URLByAppendingPathComponent:@"TrailerDB"];
  
  UIManagedDocument *doc = [[UIManagedDocument alloc] initWithFileURL:url];
  
  // If document exists on disk...
  
  if (![[NSFileManager defaultManager] fileExistsAtPath:[url path]]) 
  {
      [doc saveToURL:url 
    forSaveOperation:UIDocumentSaveForCreating
   completionHandler:^(BOOL success)
       { 
  
           if (success) [self fillDatabase:doc.managedObjectContext];
  
           if (!success) NSLog(@"couldn’t open document at %@", url);
       }];
  
  } else {   
  
      if (doc.documentState == UIDocumentStateClosed) {
          // exists on disk, but we need to open it
          [doc openWithCompletionHandler:^(BOOL success) 
           {
  
               if (success) [self fillDatabase:doc.managedObjectContext];
  
               if (!success) NSLog(@"couldn’t open document at %@", url);
           }];
      } else if (doc.documentState == UIDocumentStateNormal) 
      {
          [self fillDatabase:doc.managedObjectContext];
      }
  }
  }
  </code></pre>