我正在将数据导入核心数据的后台线程上执行 NSOperation。为此,我首先创建导入记录(“导入”),然后导入与导入记录相关的对象。如果我保存托管对象上下文,下一次将导入对象链接到导入记录的尝试将失败:
Illegal attempt to establish a relationship 'import' between objects in different contexts (source = <NSManagedObject: 0x1067bb730> (entity: Genre; id: 0x1053330c0 <x-coredata:///Genre/tC6A85CFE-3D0A-4E29-9186-4FD46104AEBC60> ; data: {
import = nil;
name = Polka;
}) , destination = <NSManagedObject: 0x106736170> (entity: Import; id: 0x103b571e0 <x-coredata://440D80CF-7C56-4B6F-9778-990032A76B8B/Import/p1> ; data: <fault>))
这是简化的代码。我稍微修改了代码,通过添加一个多余的保存来演示效果;通常没有理由在那里有一个。
NSError *writeError = nil;
TNAppDelegate *del = (TNAppDelegate *)[[NSApplication sharedApplication] delegate];
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
[moc setPersistentStoreCoordinator:[del persistentStoreCoordinator]];
[moc setUndoManager:nil];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:moc];
// create import instance
NSManagedObject *import = [NSEntityDescription insertNewObjectForEntityForName:@"Import" inManagedObjectContext:moc];
[import setValue:[NSDate date] forKey:@"start"];
[moc save:&writeError];
[moc reset];
NSString *newGenre = [songDictItem objectForKey:@"Genre"];
NSManagedObject *newGenreObject = [NSEntityDescription insertNewObjectForEntityForName:@"Genre" inManagedObjectContext:moc];
[newGenreObject setValue:newGenre forKey:@"name"];
[newGenreObject setValue:import forKey:@"import"]; // BOOM!
更新:应要求,我提供了 mergeChanges 的代码:。它可以在 NSOperation 中找到。我已经尝试了许多将更改保存到主 MOC 的变体,但它们都以相同的方式结束。
- (void)mergeChanges:(NSNotification*)notification
{
TNAppDelegate *del = (TNAppDelegate *)[[NSApplication sharedApplication] delegate];
if ([notification object] == [del managedObjectContext]) return;
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:@selector(mergeChanges:) withObject:notification waitUntilDone:YES];
return;
}
[[del managedObjectContext] mergeChangesFromContextDidSaveNotification:notification];
}