Can I connect multiple instances of NSPsistentStoreCoordinator to the same main SQLite repository?

All that I read about using Core Data in multiple threads suggests that multiple instances of NSManagedObjectContext use the same NSPersistentStoreCoordinator . This is understandable, and I did it in an application that uses the main data in the main thread in support of the user interface and has a background fetch operation, which may take some time.

The problem is that access to the underlying SQLite persistent store is serialized using NSPersistentStoreCoordinator , so there are still cases where the user interface is blocked by a background fetch operation.

A background fetch operation will never update data, but only read from it. Can I set up a completely parallel stack of Core Data ( NSManagedObjectContext , NSManagedPersistentStoreCoordinator and NSManagedObjectModel ) in a background thread connected to the same main SQLite repository? It looks like this will lead to full concurrency between the UI thread and the background fetch operation.

+7
source share
1 answer

My own preliminary answer to this is now yes .

I initialize my background operation by passing it an instance of NSPersistentStore . In the background stream, the properties of this store, including the URL, are used to create a whole new set of Core Data as follows:

  // create managed object model NSURL *modelUrl = [[NSBundle bundleForClass:[self class]] URLForResource:@"..." withExtension:@"..."]; NSManagedObjectModel *managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelUrl]; // create persistent store coordinator NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel]; NSError *error = nil; [persistentStoreCoordinator addPersistentStoreWithType:[store type] configuration:[store configurationName] URL:[store URL] options:[store options] error:&error]; // create managed object context NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; [context setPersistentStoreCoordinator:persistentStoreCoordinator]; [persistentStoreCoordinator release]; [managedObjectModel release]; 

Then I make a background selection using this newly created instance of NSManagedObjectContext .

Everything seems to be working fine. However, I am not yet accepting my own answer, as I would like someone to provide me with supporting or conflicting evidence for my findings.

+6
source

All Articles