简体   繁体   中英

Can multiple NSPersistentStoreCoordinator instances be connected to the same underlying SQLite persistent store?

Everything I've read about using Core Data on multiple threads talks about using multiple NSManagedObjectContext instances sharing a single NSPersistentStoreCoordinator . This is understood and I've made it work in an app that uses Core Data on the main thread in support of the UI and has a background fetch operation that can take a while to run.

The problem is that access to the underlying SQLite persistent store is serialized by the NSPersistentStoreCoordinator , so there are still occasions where the UI is blocked by the background fetch operation.

The background fetch operation will never update the data, only read from it. Can I set up an entirely parallel Core Data stack ( NSManagedObjectContext , NSManagedPersistentStoreCoordinator , and NSManagedObjectModel ) on the background thread connected to the same underlying SQLite persistent store? It seems like this would give complete concurrency between the UI thread and the background fetch operation.

My own tentative answer to this is now yes .

I initialize my background operation by passing it the NSPersistentStore instance. On the background thread, the properties of this store, including the URL, are used to create a whole new Core Data stack like this:

    //  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];

I then perform the background fetch using this newly created NSManagedObjectContext instance.

Everything seems to work just fine. I'm not yet accepting my own answer, though, as I would love to have someone provide supporting or contradicting evidence to my findings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM