0

NSManagedObjectContext持久存储和父上下文都设置并调用保存时会发生什么?它会将数据一一推送到持久存储和父上下文吗?还是会同时进行?或者核心数据会简单地抛出一个抱怨的异常吗?

API 不会直接阻止一个给定上下文设置两个“父母”。

4

2 回答 2

5

这将发生:

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

发生这种情况是因为当您设置 时parentContextpersistentStoreCoordinator会自动设置persistentStoreCoordinator为父上下文的 。

于 2013-03-27T06:06:20.053 回答
1

如果我们为父上下文分配协调器,我们不需要为托管上下文设置协调器

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

这是在框架示例中使用的完整代码 -

    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];
于 2017-10-19T02:46:05.210 回答