I'm trying to do a CoreData DB reset by removing a store and copying a default version in its place. The following works fine in the simulator, but when it runs on a device (testing using iOS 3.1.3 and 3.2.1) the app acts as if the database was never reset until the app is restarted. After a restart the newly initialized database is used, and everything is fine. Is there some kind of background cacheing going on that needs notification of the new store?
[I am doing error checking below, just deleting those lines for the sake of clarity. Of course, no errors are occuring]
-(void)initializeUserData {
NSError *error = nil;
NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"db.sqlite"];
NSURL *storeURL = [NSURL fileURLWithPath:storePath];
[self.managedObjectContext lock];
[self.managedObjectContext reset];
NSPersistentStore *store = [persistentStoreCoordinator persistentStoreForURL:storeURL];
[persistentStoreCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storePath error:&error];
// copy the pre-populated database file
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"db" ofType:@"sqlite"];
[[NSFileManager defaultManager] copyItemAtPath:defaultStorePath toPath:storePath error:&error];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
[persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error];
[self.managedObjectContext unlock];
}
Edit: Not sure if this means anything, but as a sanity check I turned on -com.apple.CoreData.SQLDebug and get the following logged after the call to addPersistentStoreWithType:
CoreData: annotation: Connecting to sqlite database file at "..."
The following (which I would expect to come at the call to removePersistentStore:) is logged after the app returns to the main loop:
CoreData: annotation: Disconnecting from sqlite database.
There isn't a followup "Connecting to database" message later, despite the fact that the database is being accessed, so I assume that the odd order of those log entries is just a side-effect of how logging is done...