可以将NSmanagedObject移到另一个NSManagedContext吗? [英] Possible to move NSmanagedObject to another NSManagedContext?

查看:64
本文介绍了可以将NSmanagedObject移到另一个NSManagedContext吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个NSManagedContext,一个用于父级,另一个用于子级。这样指定:

I have two NSManagedContext's, one parent and one child that i use for concurrency. Specified like this:

self.managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];

self.backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType: NSPrivateQueueConcurrencyType];
self.backgroundContext.parentContext = self.managedObjectContext;

在我的一个视图控制器中,我将此方法称为:

In one of my view controllers I call this method:

[Stream followingStreamForUser:self.user fromDictionary:dict inManagedObjectContext: [AppController sharedAppController].backgroundContext];

调用此方法会导致以下错误:

Calling this method causes the following error:

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中。

It seems like self.user isn't in my backgroundContext. I wonder if it's possible to move my self.user object to my backgroundContext or if it's possible to see where and when my user object gets added to context X.

推荐答案

如果尝试在错误的上下文中使用NSManagedObject,则在保存。

If you try to use an NSManagedObject in the wrong context you will get exceptions while saving.

如果需要从临时上下文访问现有对象,则需要使用对象的ID来获取新的实例,如下所示:

If you need to access existing objects from a temporary context, then you need to use the object's ID to get a new instance like this:

NSManagedObject *user = ...;
NSManagedObject *userInBackgroundContext = [backgroundContext objectWithID:[user objectID]];

然后,当您保存背景上下文时,更改将保存到存储中,而您只需要将这些更改恢复到您的主要环境中。

Then when you save the background context, the changes are persisted to the store, and you just need to get those changes back into your main context.

这篇关于可以将NSmanagedObject移到另一个NSManagedContext吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆