Search code examples
iphonecore-datansfetchedresultscontrollernsmanagedobjectcontext

Is NSManagedObjectContext autosaved or am I looking at NSFetchedResultsController's cache?


I'm developing an iPhone app where I use a NSFetchedResultsController in the main table view controller. I create it like this in the viewDidload of the main table view controller:

NSSortDescriptor *sortDescriptorDate = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
 NSSortDescriptor *sortDescriptorTime = [[NSSortDescriptor alloc] initWithKey:@"start" ascending:YES];
 NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptorDate,sortDescriptorTime, nil];
 [fetchRequest setSortDescriptors:sortDescriptors];
 [sortDescriptorDate release];
 [sortDescriptorTime release];
 [sortDescriptors release]; 




 controller = [[NSFetchedResultsController alloc]
      initWithFetchRequest:fetchRequest
      managedObjectContext:context
      sectionNameKeyPath:@"date"
      cacheName:nil];
 [fetchRequest release];

 NSError *error;
 BOOL success = [controller performFetch:&error];

Then, in a subsequent view, I create a new object on the context:

  TestObject *testObject = [NSEntityDescription insertNewObjectForEntityForName:@"TestObject" inManagedObjectContext:context];

The TestObject has several related object which I create in the same way and add to the testObject using the provided add...Objects methods.

Then, if before saving the context, I press cancel and go back to the main table view, nothing is shown as expected. However, if I restart the app, the object I created on the context shows in the main table view. How come? At first, I thought it was because the NSFetchedResultsController was reading from the cache, but as you can see I set this to nil just to test. Also, [context hasChanges] returns true after I restart. What am I missing here?


Solution

  • The context is never saved automatically. If you are seeing saves then there is a call to -save: somewhere. QED

    To confirm things are being written to disk are you looking at the sqlite file itself? You can peek in there to see what is being written. If there is nothing in there, perhaps you are generate default objects or something on launch.