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

后端 未结 1 709
余生分开走
余生分开走 2020-12-28 10:54

Everything I\'ve read about using Core Data on multiple threads talks about using multiple NSManagedObjectContext instances sharing a single NSPersistentS

相关标签:
1条回答
  • 2020-12-28 11:22

    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.

    0 讨论(0)
提交回复
热议问题