我需要创建 NSManagedObject 实例,用它们做一些事情,然后将它们丢弃或存储到 sqlite 数据库.问题是,我无法创建未连接到 NSManagedObjectContext 的 NSManagedObject 实例,这意味着在我决定不需要其中的某些对象后,我必须以某种方式进行清理我的数据库
I need to create NSManagedObject instances, do some stuff with them and then trash them or store to sqlite db. The problem is, I cannot create instances of NSManagedObject unconnected to NSManagedObjectContext and this means I have to clear up somehow after I decide that I don't need some of the objects in my db.
为了解决这个问题,我使用相同的协调器创建了一个内存存储,并使用 assignObject:toPersistentStore 将临时对象放置在那里. 现在,我如何确保这些临时对象对象没有访问数据,我从两个存储上下文的公共获取数据?还是我必须为这样的任务创建单独的上下文?
To deal with it, I have created an in-memory store using the same coordinator and I'm placing temporary objects there by using assignObject:toPersistentStore. Now, how do I ensure that these temporary objects don't get to the data, which I fetch from the common to both stores context? Or do I have to create separate contexts for such a task?
现在我正在考虑为内存存储创建单独的上下文.如何将对象从一个上下文移动到另一个上下文?只使用 [context insertObject:]?在这种设置下它会正常工作吗?如果我从对象图中插入一个对象,整个图是否也会插入上下文中?
Now I'm thinking about making separate context for in-memory store. How do I move objects from one context to another? Just using [context insertObject:]? Will it work OK in this setup? If I insert one object from the graph of objects, does the whole graph also get inserted into context?
推荐答案注意:这个答案非常.查看完整历史记录的评论.我的建议已经改变,我不再建议使用未关联的 NSManagedObject 实例.我目前的建议是使用临时子 NSManagedObjectContext 实例.
NOTE: This answer is very old. See comments for full history. My recommendation has since changed and I no longer recommend using unassociated NSManagedObject instances. My current recommendation is to use temporary child NSManagedObjectContext instances.
原答案
最简单的方法是创建没有关联的 NSManagedObjectContext 的 NSManagedObject 实例.
The easiest way to do this is to create your NSManagedObject instances without an associated NSManagedObjectContext.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:myMOC]; NSManagedObject *unassociatedObject = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];然后当你想保存它时:
[myMOC insertObject:unassociatedObject]; NSError *error = nil; if (![myMoc save:&error]) { //Respond to the error }更多推荐
如何处理临时 NSManagedObject 实例?
发布评论