Home > Articles > Home & Office Computing > Mac OS X

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Saving the Context

When changes are made to entities inside of a Core Data context or when entities are inserted into a context, they are not written to disk until a save request is made. Because the context already knows where the file is located, the code surrounding the save is very simple. Prior to saving the context, it is probably a good idea to commit any outstanding changes. After all the changes are committed, a save request can be sent to the context:

- (void)save {
 NSManagedObjectContext *context = [[NSApp delegate] managedObjectContext];
  if (![context commitEditing]) {
   NSLog(@"Error committing changes");
   NSBeep();
   return;
  }
  NSError *error;
  if (![context save:"error]) {
   NSLog(@"Error saving data: %@", error");
  }
}

In the above example, if there is an error committing the changes, the method will issue an error "beep" and return. Naturally, your application might want to invoke more robust reporting. If the commit was successful, a save request is sent to the context, passing in a pointer in case there is an error. If the save request returns false, the error message is sent to the log for debugging. Again in a production environment, more robust error handling is most certainly appropriate.

  • + Share This
  • 🔖 Save To Your Account