Frage

What happens when NSManagedObjectContext has both persistent store and parent context set and save is called? Will it push the data both to persistent store and the parent context one by one? Or would it do it concurrently? Or would core data simply throw a complaining exception?

API does not directly stop one from setting two "parents" for a given context.

War es hilfreich?

Lösung

This will happen:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Context already has a coordinator; cannot replace.'

This happens because when you set parentContext, the persistentStoreCoordinator is automatically set to the persistentStoreCoordinator of the parent context.

Andere Tipps

We do not need to set the coordinator for managed context if we assign the coordinator for the parent context

NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [self setManagedObjectContext:moc];

    [self setPrivateContext:[[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]];

    /// when you set parentContext, the persistentStoreCoordinator is automatically set to the persistentStoreCoordinator of the parent contex
    [self.privateContext setPersistentStoreCoordinator:coordinator];
    [self.managedObjectContext setParentContext:self.privateContext];

Here is the complete code for use in Framework example -

    NSURL *modelURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"TVModelSDK" withExtension:@"momd"];
    NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    NSAssert(mom, @"Failed to initialize mom from URL: %@", modelURL);

    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];

    NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    /// DONOT set coordinator for managed Context ! 
    // [moc setPersistentStoreCoordinator:coordinator];
    [self setManagedObjectContext:moc];

    [self setPrivateContext:[[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]];
    /// when you set parentContext, the persistentStoreCoordinator is automatically set to the persistentStoreCoordinator of the parent contex
    [self.privateContext setPersistentStoreCoordinator:coordinator];
    [self.managedObjectContext setParentContext:self.privateContext];
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top