拯救造成“非法企图建立关系......”

时间:2012-09-09 00:07:42

标签: core-data nsmanagedobjectcontext

我正在后台线程上执行NSOperation,后台线程将数据导入Core Data。我首先创建导入记录('Import'),然后导入与导入记录相关的对象。如果我保存托管对象上下文,下次尝试将导入的对象链接到导入记录将失败:

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中。我已经尝试number variations {{3}}保存对主要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];
}

1 个答案:

答案 0 :(得分:0)

直到今天,我还没弄清楚到底发生了什么。最后,我重新启动了我的项目,并从头开始设计了this tutorial。我过去曾经使用它作为参考,但不知怎的,它完全采用了他们的代码来工作。