In my application, I have the ability to clear all data from the database. Once this operation completes, a bundled JSON is then parsed and then saved to the database (in order to return the database to the default state). The operation to parse and save this JSON works fine in any case except after clearing and recreating the persistant store, in which case I get 'NSInvalidArgumentException', reason: 'Object's persistent store is not reachable from this NSManagedObjectContext's coordinator'. This exception is thrown when trying to call mergeChangesFromContextDidSaveNotification on my main thread context after saving in a background context.
Recreating the store is performed on the main thread, where as parsing and saving always occurs on a background thread. Here is the getter for my managed object context to ensure thread-safeness:
- (NSManagedObjectContext *)managedObjectContext {
NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary];
NSManagedObjectContext *threadContext = threadDictionary[ckCoreDataThreadKey];
if (!threadContext) {
threadContext = [self newManagedObjectContext];
threadDictionary[ckCoreDataThreadKey] = threadContext;
}
return threadContext;
}
the newManagedObjectContext method gives all new instances the same NSPersistentStoreCoordinator object.
Here is the code used to clear the store (performed on main thread always):
[self.managedObjectContext lock];
[self.managedObjectContext reset]; //to drop pending changes
//delete the store from the current managedObjectContext
if ([[self.managedObjectContext persistentStoreCoordinator] removePersistentStore:[[[self.managedObjectContext persistentStoreCoordinator] persistentStores] lastObject] error:error]) {
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:error];
[[self.managedObjectContext persistentStoreCoordinator] addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:error]; //recreates the persistent store
[self addSkipBackupAttributeToItemAtURL:storeURL];
}
[self.managedObjectContext unlock];
The strange part is that this same code works fine in other projects, and there are no differences other than the content of the data. Any help is greatly appreciated!