I am using CoreData backed by SQLite in my iOS application. At a certain point in the application, I want to clear all data in the database and start from scratch. I remove my NSPersistentStore from the NSPersistentStoreCoordinator, then I delete the DB file from disk, create a new file on disk, create a new NSPersistentStore and attach it to the NSPeristentStoreCoordinator. I also call the reset method my NSManagedObjectContext objects. At this point, something very strange happens. For most fetch requests to the NSManagedObjectContext, no data is returned since the database is empty. However for some subset of fetches, I get data back. This is wrong. There is no data in the database.
One solution to my problem is to create a new NSManagedObjectContext when I change the NSPersistentStore, but why should this be necessary?
Questions:
Shouldn't '[NSManagedObjectContext reset]' clear all of the caches and retrieve fresh data from the database? Why do most queries behave properly and only some return old data? I would really like to understand what caching is happening in NSManagedObjectContext or perhaps NSPersistentStoreCoordinator.
Here is the code that I run when deleting and recreating the database.
- (void) deleteDataStore
{
NSError * error = nil;
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
NSURL *storeURL = [NSURL fileURLWithPath:[self getDataStorePath]];
// Remove persistent store
for (int i=[[ self.coordinator persistentStores ] count]; i--; ) {
[ self.coordinator removePersistentStore: [[ self.coordinator persistentStores ] objectAtIndex:i] error: &error ];
}
// Delete database file
[ self deleteDataStoreInternal ];
// Recreate database
[ self createDatabase: &error options: options storeURL: storeURL ];
}
- (BOOL) deleteDataStoreInternal
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError * error = nil;
// Delete database file
if ( [fileManager fileExistsAtPath: [self getDataStorePath] ] ) {
return [fileManager removeItemAtPath: [self getDataStorePath] error: &error];
}
return YES;
}
- (BOOL) createDatabase: (NSError **) error options: (NSDictionary *) options storeURL: (NSURL *) storeURL
{
if ([self.coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:error]) {
self.isInitialized = YES;
} else {
self.isInitialized = NO;
}
return self.isInitialized;
}