NSManagedObjectContext
永続ストアと親コンテキストの両方が設定され、保存が呼び出されるとどうなりますか?データを永続ストアと親コンテキストの両方に1つずつプッシュしますか?それとも同時にそれをしますか?それとも、コアデータは単に不平を言う例外を投げますか?
APIは、特定のコンテキストに対して1つが2つの「親」を設定することを直接停止しません。
NSManagedObjectContext
永続ストアと親コンテキストの両方が設定され、保存が呼び出されるとどうなりますか?データを永続ストアと親コンテキストの両方に1つずつプッシュしますか?それとも同時にそれをしますか?それとも、コアデータは単に不平を言う例外を投げますか?
APIは、特定のコンテキストに対して1つが2つの「親」を設定することを直接停止しません。
これは起こります:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Context already has a coordinator; cannot replace.'
これは、を設定すると、が親コンテキストのに自動的に設定されるために発生parentContext
しますpersistentStoreCoordinator
。persistentStoreCoordinator
親コンテキストにコーディネーターを割り当てる場合は、マネージドコンテキストにコーディネーターを設定する必要はありません。
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];