Search code examples
ioscore-datanotificationscommitnsnotifications

Core Data commit notification


I'm using Core Data in my project and I have to save user-filled forms into Core Data DB. After user relaunches the app, a list of saved forms should show in a TableView. However, if the user exits the app before Core Data commits changes, the form is not saved. Is there any way to catch the moment when my data is commited?

This is how I save the form:

if (![document.managedObjectContext save: &error]) {
    NSLog(@"DB saving error!");
}
else {
   NSLog(@"DB save OK!");
   //show alertView
 }  

I've tried to track the Core Data commit moment using -com.apple.CoreData.SQLDebug 1. The log shows that it starts to save the object about 15 seconds later.

 // This is how my log output looks like
 2012-08-03 14:50:43.587 iPadAF_new[4506:707] DB save OK!
 2012-08-03 14:50:58.628 iPadAF_new[4506:2597] CoreData: sql: COMMIT

So how can I get the notification or something after the commit, so the user will not be able to exit the app until save?


Solution

  • You can register for NSManagedObjectContextDidSaveNotification from your context to find out when the context has been saved, or you can observe KVO notifications for the property hasChanges. I doubt those would work for, the background though, so they may not solve your problem.