可能将NSmanagedObject移动到另一个NSManagedContext?
我有两个NSManagedContext的,一个父母和一个孩子,我用于并发。 指定像这样:
self.managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; self.backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType: NSPrivateQueueConcurrencyType]; self.backgroundContext.parentContext = self.managedObjectContext;
在我的一个视图控制器中,我调用了这个方法:
[Stream followingStreamForUser:self.user fromDictionary:dict inManagedObjectContext: [AppController sharedAppController].backgroundContext];
调用此方法会导致以下错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship '[...]' between objects in different contexts
看起来像self.user
不在我的backgroundContext
。 我不知道是否有可能将我的self.user
对象移动到我的backgroundContext
或者如果可以看到我的用户对象被添加到上下文X的位置和时间。
如果您尝试在错误的上下文中使用NSManagedObject,则在保存时会出现exception。
如果您需要从临时上下文访问现有对象,那么您需要使用对象的ID来获取像这样的新实例:
NSManagedObject *user = ...; NSManagedObject *userInBackgroundContext = [backgroundContext objectWithID:[user objectID]];
然后,当您保存后台上下文时,所做的更改将被保存到存储中,您只需将这些更改返回到主上下文中即可。
上下文之间唯一可以共享的是托pipe对象ID。 你可以像这样获得它:
NSManagedObjectID *objectID = self.user.objectID;
然后从其他上下文中获取等效的对象,如下所示:
User *backgroundUser = [backgroundContext obectWithID:objectID];
backgroundUser现在可以安全地使用背景上下文中的其他对象。