Reputation: 53
Multithreading is definitely a tricky thing.
I have a Main Thread (AppDelegate), and then my app starts to send several other requests to sync some data according to some user actions. The data reads and modifies the CoreData. A Managed Object Conext is being created in each thread as Apple says.
Problem is, the "reset data base feature". That one that will simply remove all the data stored locally.
I'm doing that by removing the Persistent Store in the AppDelegate like so:
- (bool) resetCoreData
{
//Remove the persistent Store.
NSError *error;
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"insight.sqlite"];
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil];
//Borrar los conextos para que el APP lo cree despues
for (NSManagedObject *ct in [self.managedObjectContext registeredObjects]) {
[self.managedObjectContext deleteObject:ct];
}
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
//Make new persistent store for future saves
if (![self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
// TODO: handling
}
return true;
}
Then, if try to fetch data from some other thread:
*** Terminating app due to uncaught exception 'NSObjectInaccessibleException', reason: 'CoreData could not fulfill a fault for '0x1edba090 <x-coredata://5EAC46F6-54DA-480B-9B15-CB28248FD1CE/PlanResults/p7>''
Thoughts?
Upvotes: 1
Views: 149
Reputation: 6710
You need to release all NSManagedObjectContext
objects before you delete your NSPersistentStoreCoordinator
object. This needs to happen for all NSManagedObjectContext
objects in all threads. NSManagedObjectContext
objects have a persistentStoreCoordinator property.
After deleting the NSPersistentStoreCoordinator
file you can then re-create the NSManagedObjectContext
objects.
Upvotes: 1